How to manually specify the current active page with wp_nav_menu()

All we need is an easy explanation of the problem, so here it is.

Is there a way of manually specifying which page is currently “active” when using wp_nav_menu()?

I have a “Products” page, and on that page I have links to various (dynamic) custom taxonomies. When I click on one of these taxonomies, I stay on the “Products” page but wp_nav_menu() loses reference to that fact that I’m still on the “Products” page. Is there a way I can fix this?

Thanks!

Jon

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

If you just want to add the current_page_item class to one menu item, you could hook up to the nav_menu_css_class filter, and add that class if needed. It is called when the menu is printed.

If you want access to the whole menu and add classes, hook in to the wp_get_nav_menu_items filter, where you get the whole $items array. You can edit the classes properties of individual items.

Method 2

@Jon
As long as you are using <body <?php body_class(); ?>> WordPress will assign the class current_page_item to your menu along with current_page_parent if your using drop down menus.

Method 3

Jan mentioned nav_menu_css_class filter, so I looked it up and this example was helpful to me
Source: https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_css_class

function my_special_nav_class( $classes, $item ) {
    if ( is_single() && $item->title == 'Blog' ) {
        $classes[] = 'special-class';
    }
    return $classes;
}    
add_filter( 'nav_menu_css_class', 'my_special_nav_class', 10, 2 );

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply