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
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 thetheme_location
variable you can use to conditionally apply class names to a specific menu. You just need to ensure that you set thetheme_location
when you call wp_nav_menu in your theme.Here’s an example:
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, andget_nav_menu_locations()
to pull back the list of which menus are in which theme location.Modifying your code:
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.
Adding it to myself in function.php and everything will work