Skip to content

Instantly share code, notes, and snippets.

@ivankristianto
Created January 17, 2014 10:55
Show Gist options
  • Save ivankristianto/8471584 to your computer and use it in GitHub Desktop.
Save ivankristianto/8471584 to your computer and use it in GitHub Desktop.
WordPress show submenu based on active parent menu
<?php
// add hook
add_filter( 'wp_nav_menu_objects', 'my_wp_nav_menu_objects_sub_menu', 10, 2 );
// filter_hook function to react on sub_menu flag
function my_wp_nav_menu_objects_sub_menu( $sorted_menu_items, $args ) {
if ( isset( $args->sub_menu ) ) {
$root_id = 0;
// find the current menu item
foreach ( $sorted_menu_items as $menu_item ) {
if ( $menu_item->current ) {
// set the root id based on whether the current menu item has a parent or not
$root_id = ( $menu_item->menu_item_parent ) ? $menu_item->menu_item_parent : $menu_item->ID;
break;
}
}
// find the top level parent
if ( ! isset( $args->direct_parent ) ) {
$prev_root_id = $root_id;
while ( $prev_root_id != 0 ) {
foreach ( $sorted_menu_items as $menu_item ) {
if ( $menu_item->ID == $prev_root_id ) {
$prev_root_id = $menu_item->menu_item_parent;
// don't set the root_id to 0 if we've reached the top of the menu
if ( $prev_root_id != 0 ) $root_id = $menu_item->menu_item_parent;
break;
}
}
}
}
$menu_item_parents = array();
foreach ( $sorted_menu_items as $key => $item ) {
// init menu_item_parents
if ( $item->ID == $root_id ) $menu_item_parents[] = $item->ID;
if ( in_array( $item->menu_item_parent, $menu_item_parents ) ) {
// part of sub-tree: keep!
$menu_item_parents[] = $item->ID;
} else {
// not part of sub-tree: away with it!
unset( $sorted_menu_items[$key] );
}
}
return $sorted_menu_items;
} else {
return $sorted_menu_items;
}
}
$args = array(
'theme_location' => 'primary',
'container' => '',
'menu_class' => calibrefx_get_option('nav_fixed_top') ? 'navbar navbar-fixed-top menu-primary menu superfish sf-js-enabled' : 'superfish sf-js-enabled nav menu-primary menu',
'echo' => 0,
'walker' => $calibrefx->walker_nav_menu,
'sub_menu' => true,
'direct_parent' => true,
);
$nav = wp_nav_menu($args);
@macreixa
Copy link

Hello, do you know how to show menu and sub-menu on a third-level page?
A
— A1
—— A1.1
— A2
—— A2.1
B
— B1
—— B1.1
— B2
—— B2.1

So if I'm on page A1.1 I want to display de first leve menu (A, B) and the direct sub-menu (A1, A2)
I can do that only in the child pages, not in grand-child pages

Thank you
Marco

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment