duanrang2627 2017-06-25 13:20
浏览 86
已采纳

如何获取父菜单项的子项?

I have created a menu which have several items (WooCommerce categories), each of them having few child items (WooCommerce products).

I'm struggling to retrieve the sub items of a parent menu item.

Im getting the parent item using this code:

$the_menu       = wp_get_nav_menu_object('Some Menu');
$the_menu_items = wp_get_nav_menu_items($the_menu);

foreach ($the_menu_items as $index => $menu_item) {
    if ($menu_item->object_id == $category->term_id ) {
        $category_submenu = $menu_item;
    }
}

How can I retrieve the child items of current parent item?

Thank you in advance!

  • 写回答

2条回答 默认 最新

  • duanfei9278 2017-06-25 16:58
    关注

    You need a recursion for all childs.

    Here the example

    if ( ! function_exists( 'recursive_mitems_to_array' ) ) {
        /**
         * @param $items
         * @param int $parent
         *
         * @return array
         */
        function recursive_mitems_to_array( $items, $parent = 0 )
        {
            $bundle = [];
            foreach ( $items as $item ) {
                if ( $item->menu_item_parent == $parent ) {
                    $child               = recursive_mitems_to_array( $items, $item->ID );
                    $bundle[ $item->ID ] = [
                        'item'   => $item,
                        'childs' => $child
                    ];
                }
            }
    
            return $bundle;
        }
    }
    

    Usage:

    $items = wp_get_nav_menu_items( "Default Theme Menu" ); // Your menu title
    $build_tree = recursive_mitems_to_array( $items );
    
    var_dump(build_tree);
    

    Note: correct for your needs.

    maybe you need to output html with values.

    This example should return nested array (not fully tested)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图问题
  • ¥15 有段代码不知道怎么理解,const isToken = (config.headers || {}).isToken === false
  • ¥100 采用栈和深度优先算法对我的代码进行修改显示路径
  • ¥15 pointnet2包安装
  • ¥20 射频功率问题,解答者有酬谢!
  • ¥80 构建降雨和积水的预测模型
  • ¥15 #Qt Transform setTransform()在鼠标拖动移动视角是一致在原地不动,无法变换视角(细微观察似乎视图有在原地抖动),无法变换视角(细微观察似乎视图有在原地抖动)
  • ¥50 如何利用无人机拍摄的数码照片测量鸟卵的长短径
  • ¥100 github贡献者给与奖励
  • ¥15 使用DS18B20+ESP8266获取温度数据返回-127.00