仅在WordPress中具有子菜单的情况下显示菜单项

3

示例:

外观->菜单中的菜单布局

菜单名称:主菜单

关于我们(菜单) - 联系我们 (子菜单) - 团队 (子菜单) - 作品集 (子菜单)

这四个页面需要显示所有四个菜单项,包括父菜单:关于我们、联系我们、团队和作品集。

目前我只能显示子菜单项:联系我们、团队和作品集。所以我缺少父菜单。

如何同时显示父菜单项(例如:关于我们)?

这是我调用菜单的方式:

<?php // Usage:
                $args = array(
                    'menu'     => 'Main menu',
                    'sub_menu' => true,
                );
                wp_nav_menu( $args );
                ?>

这是我用于显示子菜单的功能:
// add hook
add_filter( 'wp_nav_menu_objects', 'my_wp_nav_menu_objects_sub_menu', 10, 2 );
// filter_hook function to react on sub_menu flag
function my_wp_nav_menu_objects_sub_menu( $sorted_menu_items, $args ) {
    if ( isset( $args->sub_menu ) ) {
        $root_id = 0;

        // 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;
                    }
                }
            }
        }
        $menu_item_parents = array();
        foreach ( $sorted_menu_items as $key => $item ) {
            // init menu_item_parents
            if ( $item->ID == $root_id ) $menu_item_parents[] = $item->ID;
            if ( in_array( $item->menu_item_parent, $menu_item_parents ) ) {
                // part of sub-tree: keep!
                $menu_item_parents[] = $item->ID;
            } else if ( ! ( isset( $args->show_parent ) && in_array( $item->ID, $menu_item_parents ) ) ) {
                // not part of sub-tree: away with it!
                unset( $sorted_menu_items[$key] );
            }
        }

        return $sorted_menu_items;
    } else {
        return $sorted_menu_items;
    }
}
1个回答

0
只需将'show_parent'选项添加到$args数组中,并设置为True:
$args = array(
    'menu'     => 'Main menu',
    'sub_menu' => true,
    'show_parent' => true,
);

我昨天尝试过,但现在似乎可以工作了,谢谢! - Thom van Oort

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接