Skip to content →

Highlight WordPress nav menu item based on current post

wp_nav_menu() function automatically generates css class for styling current menu item or current menu ancestor item. But in both cases your current post/page/custom post type item has to be included in the navigation menu as top menu item or sub-menu item respectively. What if your single post/page/custom post type is not included in the navigation menu but you still want to highlight it’s post type?

Let me give you an example. Lets assume we have a custom post type called “Event” and its archive page is included in our primary navigation menu as a Link. Whenever we will navigate to the archive page, wp_nav_menu() function will automatically generate “current-menu-item” css class for “Events” menu item. But if we go to any single post of “Events”, it won’t generate any specific css class unless our current post is included in the nav menu as a sub-menu item of “Events”. In this case If we still want to style/highlight “Events” menu while browsing any single Event item, we have to make use of a filter hook called by the WordPress Walker_Nav_Menu class : nav_menu_css_class.


function my_special_nav_class( $classes, $item )
//check if we are currently in single Event post. 'Events' is the link label used in our menu
    if( (is_singular('Event') && $item->title == 'Events') )
        //add custom class to 'Events' menu link
        $classes[] = 'custom-css-class';
    return $classes;

add_filter( 'nav_menu_css_class', 'my_special_nav_class', 10, 2 );


Now add necessary css styles for the custom class to highlight the “Events” menu . Thats it!

Published in WordPress Snippet


Leave a Reply

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