示例:
外观->菜单中的菜单布局
菜单名称:主菜单
关于我们(菜单) - 联系我们 (子菜单) - 团队 (子菜单) - 作品集 (子菜单)
这四个页面需要显示所有四个菜单项,包括父菜单:关于我们、联系我们、团队和作品集。
目前我只能显示子菜单项:联系我们、团队和作品集。所以我缺少父菜单。
如何同时显示父菜单项(例如:关于我们)?
这是我调用菜单的方式:
<?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;
}
}