Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kirandash/8155f98d7959d14ae583d592638877b2 to your computer and use it in GitHub Desktop.
Save kirandash/8155f98d7959d14ae583d592638877b2 to your computer and use it in GitHub Desktop.
// Usage:
$args = array(
'menu' => 'Menu Name',
'submenu' => 'About Us',
);
wp_nav_menu( $args );
//Paste this in function.php
add_filter( 'wp_nav_menu_objects', 'submenu_limit', 10, 2 );
function submenu_limit( $items, $args ) {
if ( empty($args->submenu) )
return $items;
$parent_id = array_pop( wp_filter_object_list( $items, array( 'title' => $args->submenu ), 'and', 'ID' ) );
//use 'object_id' => $args->submenu if need ID
$children = submenu_get_children_ids( $parent_id, $items );
foreach ( $items as $key => $item ) {
if ( ! in_array( $item->ID, $children ) )
unset($items[$key]);
}
return $items;
}
function submenu_get_children_ids( $id, $items ) {
$ids = wp_filter_object_list( $items, array( 'menu_item_parent' => $id ), 'and', 'ID' );
foreach ( $ids as $id ) {
$ids = array_merge( $ids, submenu_get_children_ids( $id, $items ) );
}
return $ids;
}
@Wooody82
Copy link

Wooody82 commented Oct 9, 2017

Hi,
I am not sure why its not working with me..
Notice: Only variables should be passed by reference in /wp-content/themes/mytheme/functions.php on line 12

On this line:
$parent_id = array_pop( wp_filter_object_list( $items, array( 'title' => $args->submenu ), 'and', 'ID' ) );

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