I want to get the ID of the top level ancestor in the navigation menu.
So I want to do a function that retrieves id of "TLA" from this list:
Menu
- Submenu
TLA <- Need its id
- Submenu 1
- - Submenu 2 <- active
This function echoes exactly what I need, but I actually want to return the value for using it later in a custom function:
add_filter( 'wp_nav_menu_objects', 'get_navigation_menu_root', 10, 2 );
function get_navigation_menu_root( $sorted_menu_items, $args ) {
// 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;
}
}
}
}
echo $root_id;
return $sorted_menu_items;
}
}
Aucun commentaire:
Enregistrer un commentaire