【问题标题】:Get the top most menu item of a page menu using the page id - wordpress使用页面 id 获取页面菜单的最顶部菜单项 - wordpress
【发布时间】:2020-08-06 12:27:06
【问题描述】:

我希望能够获取具有子菜单页面 ID 的子菜单的最顶层菜单项的标签。

例如: - 我有测试页面的页面 ID。所以,我想获取文本 L1,它是测试菜单的最顶层父菜单

注意:测试页面不是当前页面 - 我只有它的页面 ID。

【问题讨论】:

    标签: wordpress menu navigation


    【解决方案1】:

    我使用下面的代码来解决我的问题。

    function get_l1_menu_label( $page_id, $menu = 'primary-menu' ) {
    
        //get menu
        $all_menus = new WP_Query( [
            'post_type'         => [ 'nav_menu_item' ],
            'meta_key'          => '_menu_item_object_id',
            'meta_value'        => $page_id, // page id here
            'tax_query'         => [
                [
                    'taxonomy'  => 'nav_menu',
                    'field'     => 'slug',
                    'terms'     => $menu, //menu slug here
                ]
            ],
            'fields'            => 'ids'
        ] );
    
        $current_page_menu_id = $all_menus->posts[0];
    
        if ( !$current_page_menu_id ) {
            //looks like the page is not menu
             return '';
        }
    
        $parent_menu_id = (int) get_parent_menu_label_recursion($current_page_menu_id);
    
        //get the custom nav title set in menu admin
        $title = get_the_title( $parent_menu_id );
    
        if ( $title !== '' ) {
            return $title;
        } else {
            //the page orginal title is the label
            $parent_menu_page_id =  get_post_meta( $parent_menu_id, '_menu_item_object_id', true );
            return get_the_title( $parent_menu_page_id );
        }
    }
    
    //recursive function to fetch a top most parent id in nav menu
    function get_parent_menu_label_recursion($menu_id) {
        
        $parent_menu_id = (int) get_post_meta( $menu_id, '_menu_item_menu_item_parent', true );
        
        if ( $parent_menu_id !== 0 ) {
            //the parent exist - send the parent menu
            return get_parent_menu_label_recursion($parent_menu_id);
        } else {
            //the menu sent to this function is the top most menu
            return $menu_id;
        }
    }
    

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2014-08-01
      • 2015-08-04
      • 1970-01-01
      • 2013-11-30
      • 2017-02-08
      相关资源
      最近更新 更多