WordPress: Add/Override CSS classes for navigation menu item
I just started learning WordPress again!!! And I’m writing a custom theme backed by plugin to have a combo for full functional website.
When I started to make navigation, I need to add the custom CSS class on the <li> item and also the ‘active’ class for the current item.
For adding the custom CSS class through WordPress dashboard, I get help from press customizr. However, I need to add the ‘active’ class for the current page. After digging inside WordPress core code, I found a filter which is easy to implement than writing a complete walker class. And following is the sample code which I want to share with others so anyone who is starting to learn WordPress or looking for easy way to implement this can save their time.
The filter ‘nav_menu_css_class’ takes 4 input parameters and based on that we can implement our custom logic to add the ‘active’ class for the current page.
In my theme, I just have a top level menu and hence the above logic is no checking any depth. But we can easily implement to check the depth and add the css class for the active child page as well.
Happy WordPressing!!!!