6

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')?

Regards,

Daniel

14

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;
}
| improve this answer | |
  • in my case, i called the menu via wp_nav_menu( ['menu' => 'main'] ); so the $args->theme_location was empty. but the $args->name wasn't (since i only set this..), so i went with this attribute and it works.. – honk31 Feb 23 '17 at 16:39
3

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;
}
| improve this answer | |
1

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' ) ); ?>
| improve this answer | |
  • Thanks for the response but I need a class for the menu items (li), not the whole menu (ul). – Daniel Baars Mar 13 '13 at 16:07
0

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;
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.