只有在Wordpress中有子菜单时才显示菜单项

时间:2017-05-02 15:04:14

标签: php wordpress function loops menu

示例:

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

菜单名称:主菜单

关于我们(菜单) - 联系(子菜单) - 团队(子菜单) - 投资组合(子菜单)

这四个页面需要显示所有四个菜单项,包括父母:关于我们,联系人,团队和投资组合。

目前我只能这样显示子菜单项:联系人,团队和投资组合。所以我想念父母。

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

这就是我调用菜单的方式:

<?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 :(得分:0)

只需添加&#39; show_parent&#39; $ args数组的选项并将其设置为True:

$args = array(
    'menu'     => 'Main menu',
    'sub_menu' => true,
    'show_parent' => true,
);
相关问题