最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to get the name of the parent menu if the current page is an archive page in a custom menu

programmeradmin0浏览0评论
<?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 badges
Add a comment  | 

1 Answer 1

Reset to default 1

https://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>";
}
发布评论

评论列表(0)

  1. 暂无评论