Add class to menu items of one specific menu (nav_menu_css_class)

This code adds an extra class to all my menu items:

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
function special_nav_class($classes, $item){
  $classes[] = 'btn';
  return $classes;
}

How do I confine this filter to my main menu (in theme location ‘primary-menu’)?

Read More

Regards,

Daniel

Related posts

Leave a Reply

4 comments

  1. I was also trying to solve this problem and while searching for a solution, discovered that the nav_menu_css_class filter actually excepts a third parameter. This is an object containing variables related to your menu and includes the theme_location variable you can use to conditionally apply class names to a specific menu. You just need to ensure that you set the theme_location when you call wp_nav_menu in your theme.
    Here’s an example:

    add_filter( 'nav_menu_css_class', 'special_nav_class', 10, 3 );
    function special_nav_class( $classes, $item, $args ) {
        if ( 'primary-menu' === $args->theme_location ) {
            $classes[] = 'btn';
        }
    
        return $classes;
    }
    
  2. I came across this thread trying to solve the same problem – this is what I’ve come up with. I don’t know how well this performs, since it’ll be called for every single menu item, but it seems menus are set up as taxonomies inside WordPress, and so you can use has_term() to determine if the item is in a particular menu, and get_nav_menu_locations() to pull back the list of which menus are in which theme location.

    Modifying your code:

    add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
    function special_nav_class($classes, $item){
        $menu_locations = get_nav_menu_locations();
        if ( has_term($menu_locations['primary-menu'], 'nav_menu', $item) ) {
            $classes[] = 'btn';
        }
        return $classes;
    }
    
  3. You don’t need to modify your functions.php. Just go into your template file and find wp_nav_menu and add ‘menu_class’ to it.

    <?php wp_nav_menu( array( 'theme_location' => 'primary','menu_class' => 'newmenuclass' ) ); ?>
    
  4. Adding it to myself in function.php and everything will work

    add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);
    
    
    function special_nav_class ($classes, $item) {
    
        $classes[] = 'nav__link';
    
        if (in_array('current-menu-item', $classes) ){
    
            $classes[] = 'nav__link-active';
    
        }
    
        return $classes;
    }