Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom set "current-menu-item" class for specific pages in WP

I'm creating a custom WP theme and I'm using the Wordpress navigation bar. When switching between different pages, WP adds a "current-menu-item" class to link in navigation bar which corresponds to the current page.

However, if that page/post is not present in the nav bar, it doesn't add the "current-menu-item" to any of the nav bar items.

My problem is, when a user visits the page "BLOG" (which is actually a category page) and clicks on a certain post which opens the single.php template, I want the nav bar item "BLOG" to be underlined as it would if the visitor was visiting a blog page.

Sometimes I will want another nav bar item to be underlined when landing on SINGLE, depending on where the user came from (I also have homepage posts, then I'd like HOME to be underlined)

How do I accomplish this? Thanks.

like image 212
Zannix Avatar asked Jan 09 '14 12:01

Zannix


1 Answers

You can use a filter and check what page you are currently on using conditional statements and add classes before the menu gets displayed:

function add_custom_classes($classes, $item){
    if(is_single() && $item->title == 'BLOG'){
         $classes[] = 'current-menu-item';
    }
    return $classes;
}

add_filter('nav_menu_css_class' , 'add_custom_classes' , 10 , 2);
like image 134
Hunter WebDev Avatar answered Nov 10 '22 17:11

Hunter WebDev