Adding custom CSS class to list items in WordPress navigation menu

I’m working on a WordPress site and need some help with the navigation menu. I’m using the wp_nav_menu() function to display the menu, but I want to add my own CSS class to each list item.

Here’s what I’m trying to achieve:

<li class='custom_class'><a href=''>Menu Item</a></li>

I’ve looked through the WordPress Codex, but I’m not sure which parameters or filters to use. Does anyone know how to add a custom class to the <li> elements in the menu?

I’d appreciate any tips or code examples that could help me solve this. Thanks in advance for your help!

hey, there’s a simpler way i use. just add this to ur functions.php:

add_filter('nav_menu_css_class', function($classes) {
    $classes[] = 'custom_class';
    return $classes;
});

it adds the class to all menu items. quick n easy!

Another approach you might consider is using the ‘wp_nav_menu_objects’ filter. This gives you more flexibility to modify menu items before they’re rendered. Here’s a snippet you can add to your functions.php:

function add_custom_class_to_menu($items, $args) {
    foreach($items as &$item) {
        $item->classes[] = 'custom_class';
    }
    return $items;
}
add_filter('wp_nav_menu_objects', 'add_custom_class_to_menu', 10, 2);

This method allows you to add classes based on specific conditions if needed. For instance, you could check $item->object_id to add classes only to certain menu items. It’s a bit more involved than the nav_menu_css_class filter, but it offers greater control over the menu structure.

I’ve dealt with this exact issue before, and there’s a straightforward solution using the ‘nav_menu_css_class’ filter. Here’s what worked for me:

Add this code to your theme’s functions.php file:

function add_custom_class_to_menu_items($classes, $item, $args) {
    $classes[] = 'custom_class';
    return $classes;
}
add_filter('nav_menu_css_class', 'add_custom_class_to_menu_items', 10, 3);

This filter adds ‘custom_class’ to every menu item. If you need more control, you can modify the function to add the class conditionally based on menu location, item properties, etc.

Remember to clear your cache after making changes. This approach is clean and doesn’t require modifying core WordPress files, which is always a plus for maintainability.