Add a CSS class to a menu or menu item in WordPress

CSS Classes can be added to a WordPress menu via a filter named – wp_nav_menu_args , a number of other parameters can also be added. Another filter nav_menu_css_class can also be used for actual list items.

Adding a CSS Class to a menu

function modify_nav_menu_args( $args ) {
 if( 'primary' == $args['theme_location'] ) {
 $args['menu_class'] = 'menu genesis-nav-menu menu-primary nav-menu special-class';
   }
return $args;
}
add_filter( 'wp_nav_menu_args', 'modify_nav_menu_args' );

Appending a CSS Class to a menu

function modify_nav_menu_args( $args ) {
 if( 'primary' == $args['theme_location'] ) {
 $args['menu_class'] .= ' special-class';
   }
return $args;
}
add_filter( 'wp_nav_menu_args', 'modify_nav_menu_args' );

In the first code block above, the primary menu is targetted by saying that if the primary is equal to the theme location, then that is the one that gets the CSS classes, then the menu_class is assigned the CSS classes, space separated for multiple values.

You need to rewrite the original CSS classes it has and append the new classes at the end.

In the second code block, a new CSS class is appended to the original classes by using a period ‘.’ just before the equals, then add in the extra class in quotes with a preceding space, otherwise the class names will mash.

If you didn’t have the theme location set, then you can just remove that if statement and the class will be applied to all menus.

Adding a CSS Class to all menu items

The other filter allows the list item to have the CSS class added.

function special_nav_class( $classes, $item ){
 if( is_home() ){ 
 $classes[] = "special-class";
 }
 return $classes;
}
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

So here a condition is set that the extra class only appears on the home page, you just need to add in the extra CSS class to the $classes array, it will be appended to the existing ones. The class would be applied to all menu list items.

Adding a CSS Class to a specific menu item

You can also use a second argument $item which you can choose a range of parameters of the nav menu item data object. So now we can make a more granular target of an individual menu list item.

function special_nav_class( $classes, $item ){
 if( is_home() && $item->title == 'Home' ){ 
 $classes[] = "special-class";
 }
 return $classes;
}
add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

So here the object $item is passed in with a value of ‘Home’ set to the title or link text of the menu item and now only that menu item will have the extra menu class added.

Leave a Comment





%d bloggers like this: