Latest Tech and Tips

Add a Custom Class in WordPress Menu Item using Conditional Statements

1

In most circumstances when styling WordPress navigation menus, you’ll be able to merely add CSS courses from the WordPress admin panel. Recently whereas engaged on a mission, we discovered ourselves in a troublesome scenario. We wished so as to add a customized class to a particular menu merchandise solely on single put up pages. After trying round for a whereas, we couldn’t discover any resolution. Our final resort was to ask on twitter. Otto (@Otto42) replied by saying it’s potential by using filters, however there aren’t any documentation for the filter.

After trying in the core for a whereas, we found out the answer. What it is advisable 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);
perform special_nav_class($courses, $merchandise){
     if(is_single() && $item->title == 'Blog'){
             $courses[] = 'current-menu-item';
     }
     return $courses;
}

The code above is just checking whether it is a single put up web page, and the menu merchandise title is Blog. If the standards is matched, then it’s including a class “Current-menu-item”. We wanted so as to add a customized class in order to make it work with this design that we’re engaged on.

If you’ll be able to’t inform already, mainly what we wished to do was preserve the weblog merchandise highlighted in the menu when the consumer was on a single put up. This allowed them to see that the only posts are a part of the weblog. This usually doesn’t make sense, however in the design that we’re engaged on, it did make sense.

If you had been determined on the lookout for this code, we hope that this text helped. You can verify for different $merchandise variables additionally. Some examples are: $item->ID, $item->title, $item->xfn

Quick Edit: After posting this text on twitter, one in every of our customers @dbrabyn identified that we might’ve simply completed this with CSS Body courses. For instance:

.single #navigation .leftmenublog div{show: inline-block !vital;}

Basically what we did was added a further div to show an arrow icon to our menu. This arrow would solely be proven if the category was both hovered over, or chosen. Otherwise it was set to show: none; By using the physique class, we simply made the div factor show just for the particular menu class.