我猜您将在主菜单中使用页面或类别。需要修改以下代码才能用于自定义分类法(也可以用于自定义帖子类型)。
将以下代码放入主题函数中。php:
function km_dynamic_secondary_menu_reg() {
global $km_nav_menus;
$theme_location = \'primary\'; // replace with the primary registered nav menu
$locations = get_nav_menu_locations();
$menu_items = wp_get_nav_menu_items( $locations[$theme_location] );
if ( isset($menu_items) && !empty($menu_items) ) {
$km_nav_menus = array();
foreach( $menu_items as $item ) {
if ( \'post_type\' == $item->type ) {
$post_type = ( \'page\' == $item->object ) ? $item->object : \'post\';
$km_nav_menus[get_post_field( \'post_name\', $item->object_id ).\'-\'. $post_type] = \'"\'.$item->title . \'" Secondary Menu\';
register_nav_menus( $km_nav_menus );
} elseif ( \'taxonomy\' == $item->type ) {
$km_nav_menus[get_term_field( \'slug\', $item->object_id, $item->object ).\'-tax\'] = \'"\'.$item->title . \'" Secondary Menu\';
register_nav_menus( $km_nav_menus );
} else {
//Your default fallback if needed
}
}
}
}
add_action( \'init\', \'km_dynamic_secondary_menu_reg\' );
您需要将主菜单slug分配给
$theme_location
在上述代码中。
执行上述代码后,您应该会在仪表板->外观->菜单部分中根据主菜单中的项目看到额外注册的菜单。这将是动态的,取决于您的主菜单。
现在,您需要做的最后一件事是在您想要显示辅助菜单的任何地方输出以下代码。
global $km_nav_menus;
if ( function_exists( \'wp_nav_menu\' ) ) {
foreach( $km_nav_menus as $key => $value ) {
$p_menu_item = explode( \'-\', $key );
if ( \'tax\' == $p_menu_item[count($p_menu_item)-1] ) {
unset($p_menu_item[count($p_menu_item)-1]);
if ( is_category( implode( \'-\', $p_menu_item ) ) || is_tag( implode( \'-\', $p_menu_item ) ) ){
if ( has_nav_menu( $key ) )
wp_nav_menu( array( \'theme_location\' => $key ) );
break;
}
}
if ( \'page\' == $p_menu_item[count($p_menu_item)-1] ) {
unset($p_menu_item[count($p_menu_item)-1]);
if ( is_page(implode( \'-\', $p_menu_item ) ) ){
if ( has_nav_menu( $key ) )
wp_nav_menu( array( \'theme_location\' => $key ) );
break;
}
}
if( \'post\' == $p_menu_item[count($p_menu_item)-1] ) {
unset($p_menu_item[count($p_menu_item)-1]);
if ( is_single(implode( \'-\', $p_menu_item ) ) ){
if ( has_nav_menu( $key ) )
wp_nav_menu( array( \'theme_location\' => $key ) );
break;
}
}
}
}