我正在使用wp_nav_menu
对于我只想在有子菜单项要显示时显示的子菜单(包括周围的html)。
问题是,函数总是返回菜单项(应该返回时),或者返回空列表(没有显示时)。我需要它(并且认为它会)返回false。
这是我的密码。
// Capture submenu as a variable
$args = array(
\'theme_location\' => $in_menu,
\'echo\' => \'0\',
\'sub_menu\' => true,
\'fallback_cb\' => \'coepio_return_false\'
); // Note I\'ve also tried \'fallback_cb\' => false with the same result
$submenu = wp_nav_menu( $args );
// If the menu exists
if( $submenu ) {
?>
<div id="submenu" class="sidebar cf" role="navigation">
<div class="widget">
<div id="submenu-title" class="widget-title">
<h4>In This Section</h4>
</div>
<div class="widget-content">
<?php
echo $submenu;
?>
</div>
</div>
</div><!-- #submenu -->
<?php
}
如果你注意到了
\'sub_menu\' => true
你有一双好眼睛。这是代码。
// Submenus - required for the submenu (above) to work
// filter_hook function to react on sub_menu flag
function coepio_submenu( $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;
}
}
$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 {
// not part of sub-tree: away with it!
unset( $sorted_menu_items[$key] );
}
}
return $sorted_menu_items;
} else {
return $sorted_menu_items;
}
}
add_filter( \'wp_nav_menu_objects\', \'coepio_submenu\', 10, 2 );
SO网友:Eric K
我遇到了这个问题,我的bug来自于我写错的其他代码。我有以下代码处理$查询:
function qd_post_queries( $query ) {
if(is_tax(\'qd_locations\')){
$query->set(\'post_type\',\'qd_program\');
}
}
add_action( \'pre_get_posts\', \'qd_post_queries\' );
这导致了对分类法页面上的每个查询的劫持,包括对导航的调用。我需要添加
is_main_query()
到
if
要解决此问题,请执行以下操作:
if(is_tax(\'qd_locations\') && $query->is_main_query())