WordPress

Style A Specific WordPress Menu Item

The following code snippet will allow you to style a specific menu item differently to the other items.

When WordPress creates a menu it will use the menus setup in the WordPress admin, this interface gives the user full flexibility of the what items go in the menu and where they are positioned in the theme.

WordPress will automatically add ID's and Classes to these menus so that you can style them in your theme stylesheet. There are different ways that you can style a specific menu item, WordPress will add an ID to the list item of the menu, so you can use this in your stylesheet. But the problem with this is that it will use the ID of the database, so if your working over different development environments or if this menu item is deleted and re-added the ID's will be different.

A better solution will be to run off the title of the menu item, for example if you have a navigation bar and would want to style the home page link different to the other pages then you can use the following code.

add_filter('nav_menu_css_class' , 'conditional_nav_menu_class' , 10 , 2);
function conditional_nav_menu_class($classes, $item){
     if( strtolower($item->title) == "home" ){ 
             $classes[] = "home-icon";
     }
     return $classes;
}

This code uses the filter nav_menu_css_class which will allow you to change the the classes that are added to the menu items. Because there are a number of classes that are added we need to return an array of CSS classes to go onto the menu item.

To add the extra CSS class we just need to check that the menu item title equals home, then we can add a CSS class of home-icon to the classes array.

Back to top