i have a problem displaying only the menu with wp_nav_menu, in which the current-menu-item is in.
Heres what i got:
function register_menus() {
register_nav_menus(
array(
'sidebar-menu' => __('Sidebar Menu'),
'first-menu' => __('Menu 1'),
'second-menu' => __('Menu 2'),
'third-menu' => __('Menu 3')
)
);
}
add_action('init', 'register_menus')
and on the page.php i’m doing
<?php wp_nav_menu(array('theme_location' => 'first-menu')); ?>
<?php wp_nav_menu(array('theme_location' => 'second-menu')); ?>
<?php wp_nav_menu(array('theme_location' => 'third-menu')); ?>
when i now open up a page, which is in Menu 2, i can style it with .current-menu-item – so no problem here.
but i want to display only the one menu, which has the .current-menu-item in it (Menu 2). the other ones (Menu 1, Menu 3) should be display: none;
is there a way to accomplish that?
i thought of a walker, a filter or a simple if-statement, which checks for the menu, which has the .current-menu-item but i can’t handle it myself 🙁
thank you very much
1 Answer
Just intercept the nav classes and search for the current-menu-item
class. This will give you the $item
it’s associated with.
add_filter( 'nav_menu_css_class', 'get_active_class', 10, 2 );
function get_active_class( $classes, $item )
{
if ( in_array( 'current-menu-item', $classes) ) {
// We found the active class!: $item
}
return $classes;
}
Now just grab your nav menu and apply the needed css classes or style="display:none"
to the others.