如果菜单是通过生成的wp_nav_menu
, 您可以使用自定义Walker向特定项目添加动态子菜单。
首先是课堂,这将成为你的主题functions.php
文件或您自己的自定义插件:
class Walker_Author_Categories extends Walker_Nav_Menu {
// we only need to override the function that closes each menu item,
// this is where we can insert a submenu
function end_el( &$output, $item, $depth=0, $args=array() ) {
// if the current menu item being output is authors
if( \'authors\' == $item->title ){
// get all of the author categories
$author_cats = get_terms( array(
\'taxonomy\' => \'author_categories\',
\'hide_empty\' => false,
) );
if ( ! empty( $author_cats ) && ! is_wp_error( $author_cats ) ) {
// url of the authors page
// to be used to append #anchor links
$parent_url = get_permalink( $item->object_id );
// start a new list
$output .= \'<ul>\';
// iterate over each category
// and add an li
foreach( $author_cats as $author_cat ){
$slug = $author_cat->slug;
$name = $author_cat->name;
$format = \'<li><a href="%s#%s">%s</a></li>\';
$output .= sprintf( $format, $parent_url, $slug, $name );
}
// close the list
$output .= \'</ul>\';
}
}
// close the parent li
$output .= "</li>\\n";
}
}
然后,在输出菜单的位置,添加自定义walker:
wp_nav_menu( array(
\'theme_location\' => \'primary\',
\'walker\' => new Walker_Author_Categories
) );