这是我在子菜单中使用的一个函数,也许有更好的方法可以做到这一点,但我最终总是得到这个解决方案。将此函数添加到主题函数中。php文件:
function wpse_submenu( $id, $echo = false, $showParent = true, $depth = 0 ) {
global $wpdb, $post, $before, $page_for_posts;
// if is a page
if( get_post_type() == \'post\' || is_paged() ) {
$id = get_option(\'page_for_posts\');
}
$the_post_ID = $id;
$page_id = get_page( $id );
_get_post_ancestors( $page_id );
$ancestors = array_filter( $page_id->ancestors );
$parent_id = count( $ancestors ) > 0 ? $ancestors[ count( $ancestors ) - 1] : $id;
$post->ID = $id;
$page_query = get_page( $parent_id );
$parent_title = $page_query->post_title;
$page_menu = wp_list_pages(\' echo=0&depth=\'. $depth .\'&title_li=&child_of=\'. $parent_id );
wp_reset_query();
// echo or not
if( $echo ){
$sub_pages = explode( "\\n", $page_menu );
// add class first and last class
$last = (count( $sub_pages ) - 2);
$sub_pages[0] = str_replace( \'class="\', \'class="first \', $sub_pages[0] ); // first
$sub_pages[$last] = str_replace( \'class="\', \'class="last \', $sub_pages[$last] ); // last
// if the parent is the current page
if( $the_post_ID == $parent_id ){
$class = " current_page_item";
} else {
$class = "";
}
echo \'<ul class="pagenav">\';
// if to show the parent in the menu
if( $showParent ){
echo \'<li class="parent-page page_item\'. $class .\'" ><a href="\'. get_permalink( $parent_id ) .\'">\'. $parent_title .\'</a></li>\';
}
// echo all the pages
foreach( $sub_pages as $page ){
echo $page ."\\n";
}
echo \'</ul>\';
} else {
return $page_menu;
}
}
并将其放置在您希望显示子菜单的位置:
<?php if( wpse_submenu( $post->ID ) ) wpse_submenu( $post->ID, true, false ); ?>
和som basic css,在第一级时将隐藏子页面:
.pagenav ul {
display: none;
}
.pagenav .current_page_parent .children,
.pagenav .current_page_ancestor .children,
.pagenav .current_page_item .children {
display: block;
}