Last active
November 1, 2022 02:43
-
-
Save levymetal/422c56120964a05ff31b to your computer and use it in GitHub Desktop.
Custom adaptation for my sub-menu script that treats first-level items as root-level items. Full documentation here: http://christianvarga.com/how-to-get-submenu-items-from-a-wordpress-menu-based-on-parent-or-sibling/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** wp_nav_menu( array( | |
'theme_location' => 'primary', | |
'sub_menu' => true | |
) ); | |
or | |
wp_nav_menu( array( | |
'theme_location' => 'primary', | |
'sub_menu' => true, | |
'show_parent' => true | |
) ); | |
do not use direct_parent! | |
**/ | |
// 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; | |
// treat first level items as root level items | |
$root_level_items = array( 0 ); | |
foreach ( $sorted_menu_items as $menu_item ) { | |
if ( $menu_item->menu_item_parent == 0 ) $root_level_items[] = $menu_item->ID; | |
} | |
// 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 && ! in_array( $menu_item->menu_item_parent, $root_level_items ) ) ? $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 ( ! in_array( $prev_root_id, $root_level_items ) ) { | |
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 ( ! in_array( $prev_root_id, $root_level_items ) ) $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 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment