Skip to content

Instantly share code, notes, and snippets.

@levymetal
Last active November 1, 2022 02:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save levymetal/d6d76c0988f786cdffe1615995b14cfb to your computer and use it in GitHub Desktop.
Save levymetal/d6d76c0988f786cdffe1615995b14cfb to your computer and use it in GitHub Desktop.
<?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 ) ) {
$current_id = 0;
$root_id = 0;
// find the current menu item
foreach ( $sorted_menu_items as $menu_item ) {
if ( $menu_item->current ) {
// store the current menu item
$current_id = $menu_item->ID;
// 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 current menu items children
foreach ( $sorted_menu_items as $menu_item ) {
if ( $menu_item->menu_item_parent == $current_id ) {
// it has children, make sure the root id is current menu item
$root_id = $current_id;
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 if ( ! ( isset( $args->show_parent ) && in_array( $item->ID, $menu_item_parents ) ) ) {
// not part of sub-tree: away with it!
unset( $sorted_menu_items[$key] );
}
}
return $sorted_menu_items;
} else {
return $sorted_menu_items;
}
}
@Nikita-Sp
Copy link

Great!
Thanks!

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