Add a Custom Class in WordPress Menu Item using Conditional Statements

Most often when styling WordPress navigation menus, you’ll be able to merely add CSS lessons from the WordPress admin panel. Lately whereas engaged on a challenge, we discovered ourselves in a hard scenario. We needed so as to add a customized class to a selected menu merchandise solely on single publish pages. After wanting round for some time, we couldn’t discover any answer. Our final resort was to ask on twitter. Otto (@Otto42) replied by saying it’s doable through the use of filters, however there aren’t any documentation for the filter.

After wanting within the core for some time, we found out the answer. What it’s worthwhile to do is paste the next code in your capabilities.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 just checking if it’s a single publish web page, and the menu merchandise title is Weblog. If the standards is matched, then it’s including a categoryPresent-menu-item”. We would have liked so as to add a customized class with the intention to make it work with this design that we’re engaged on.

In case you can’t inform already, mainly what we needed to do was maintain the weblog merchandise highlighted within the menu when the consumer was on a single publish. This allowed them to see that the only posts are a part of the weblog. This usually doesn’t make sense, however within the design that we’re engaged on, it did make sense.

You May Also Like : Auto-Redirect when WordPress Search Query Only Returns One Match

In case you had been determined in search of this code, we hope that this text helped. You’ll be able to verify for different $merchandise variables additionally. Some examples are: $item->ID, $item->title, $item->xfn

Fast Edit: After posting this text on twitter, considered one of our customers @dbrabyn identified that we might’ve simply achieved this with CSS Physique lessons. For instance:

.single #navigation .leftmenublog div

Principally what we did was added an extra div to show an arrow icon to our menu. This arrow would solely be proven if the category was both hovered over, or chosen. In any other case it was set to show: none; Through the use of the physique class, we simply made the div factor show just for the precise menu class.

If you liked this article, make sure to hit the bell for getting our latest updates and share this article with your friends in every social media platforms.

1 thought on “Add a Custom Class in WordPress Menu Item using Conditional Statements”

  1. Pingback: How to Disable WordPress Admin Bar for All Users Except Administrators

Leave a Comment

Your email address will not be published. Required fields are marked *