<?php
// print_r(get_queried_object_id());
$primaryNav = wp_get_nav_menu_items(2);
print_r(get_menu_parent(2));
foreach ($primaryNav as $navItem) {
if (!empty($navItem->menu_item_parent) && $navItem->object_id == get_queried_object_id()) {
echo '<span>' . get_post($navItem->menu_item_parent)->post_title . '</span>';
}
} ?>
So far in the page I got the parent menu name with object_id.
However, if you go to the post-type page from the menu, the object_id is 0, so the parent menu cannot be imported. What do I need to fix
<?php
// print_r(get_queried_object_id());
$primaryNav = wp_get_nav_menu_items(2);
print_r(get_menu_parent(2));
foreach ($primaryNav as $navItem) {
if (!empty($navItem->menu_item_parent) && $navItem->object_id == get_queried_object_id()) {
echo '<span>' . get_post($navItem->menu_item_parent)->post_title . '</span>';
}
} ?>
So far in the page I got the parent menu name with object_id.
However, if you go to the post-type page from the menu, the object_id is 0, so the parent menu cannot be imported. What do I need to fix
Share Improve this question asked Jan 30, 2021 at 9:53 sanghyeonsanghyeon 215 bronze badges1 Answer
Reset to default 1https://stackoverflow/questions/52006212/how-to-get-current-page-menu-item-ancestor-name-wordpress
I found a solution through the answers to the above questions.
function my_menu_parent($theme_location) {
$locations = get_nav_menu_locations();
if ( isset( $locations[ $theme_location ] ) ) {
$menu = wp_get_nav_menu_object( $locations[ $theme_location ] );
$menu_items = wp_get_nav_menu_items($menu->term_id);
_wp_menu_item_classes_by_context( $menu_items );
$breadcrumbs = array();
foreach ( $menu_items as $menu_item ) {
if ($menu_item->current_item_ancestor) {
$breadcrumbs[] = $menu_item->title;
}
}
return $breadcrumbs;
}
}
<?php
$parentitems = my_menu_parent( 'menu-1' );
foreach ( $parentitems as $parentitem ) {
echo $parentitem."<br>";
}