Add a Custom Class in WordPress Menu Item using Conditional Statements


In most cases when styling WordPress navigation menus, you can simply add CSS classes from the WordPress admin panel. Recently while working on a project, we found ourselves in a troublesome situation. We wanted to add a custom class to a specific menu item only on single post pages. After looking around for a while, we could not find any solution. Our last resort was to ask on twitter. Otto (@Otto42) replied by saying it is possible by using filters, but there are no documentation for the filter.

After looking in the core for a while, we figured out the solution. What you need to do is paste the following code in your functions.php file:

  //Filtering a Class in Navigation Menu Item  add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);  function special_nav_class($classes, $item){       if(is_single() && $item->title == 'Blog'){               $classes[] = 'current-menu-item';       }       return $classes;  }  

The code above is simply checking if it is a single post page, and the menu item title is Blog. If the criteria is matched, then it is adding a class “Current-menu-item”. We needed to add a custom class in order to make it work with this design that we are working on.

If you can’t tell already, basically what we wanted to do was keep the blog item highlighted in the menu when the user was on a single post. This allowed them to see that the single posts are part of the blog. This normally doesn’t make sense, but in the design that we are working on, it did make sense.

If you were desperate looking for this code, we hope that this article helped. You can check for other $item variables also. Some examples are: $item->ID, $item->title, $item->xfn

Quick Edit: After posting this article on twitter, one of our users @dbrabyn pointed out that we could’ve easily accomplished this with CSS Body classes. For example:

.single #navigation .leftmenublog div{display: inline-block !important;}

Basically what we did was added an additional div to display an arrow icon to our menu. This arrow would only be shown if the class was either hovered over, or selected. Otherwise it was set to display: none; By using the body class, we just made the div element display only for the specific menu class.