忘记插件吧,我也有同样的问题,插件造成了一大堆混乱和太多的db调用。
此代码将为您完成业务—为便于使用,请将其粘贴到内容部分并按如下方式包含:
get_template_part( \'subnav\', \'pagename\' );
问题是,你已经了解你的孩子,你也了解你的父母。我尝试使用wp list pages函数,将echo设置为false并包含id,但这有点混乱。这个解决方案并不完美,但比使用一两个插件要干净得多。
简而言之,您需要绝对的顶级父id,然后需要获取当前帖子祖先的所有子项:
function get_top_id($id){
$parents = get_post_ancestors( $post );
return $parents[count($parents)-1];
}
function get_sub_pages($id){
global $post;
// get the ancestors for this depth
$parents = get_post_ancestors( $post );
//add the post id to the list in order to get the children
array_unshift($parents, $post->ID);
//reverse the order of the array
$parents = array_reverse($parents);
// specify to get all children of the top level parent
$args = array( \'child_of\' => $id);
if($subPages = get_pages($args)):
// start at the first $parents array key
$curParent = 0;
$childList = \'<ul>\';
if($id == $post->ID) $class = \' class="selected"\';
$childList .= "<li" . $class ."><a href=\'". get_page_link( $id )."\'>Introduction</a></li>" ;
foreach( $subPages as $page ) :
// only add the item if:
// a: the pages parent is in the ancestors array
if(in_array($page->post_parent, $parents)){
// get the key of the page parent within the $parents array
// this helps us check if we are going to a deeper/higher level
$pageParent = array_search($page->post_parent, $parents);
if($curParent != $pageParent){
// if we are going deeper, add a new list for the children
if($pageParent > $curParent){
$childList .= \'<ul>\';
}
// if we are going higher, check how many depth changes
if($pageParent < $curParent){
$depthChange = $curParent - $pageParent;
// close off all the children of higher depths
while($depthChange > 0){
$childList .= \'</li></ul>\';
$depthChange --;
}
}
// set the new parent level
$curParent = $pageParent;
}
$class = \'\';
if($page->ID == $post->ID) $class = \' class="selected"\';
if($page->ID == $post->post_parent) $class = \' class="parent"\';
// leave off the trailing <li> in case there are children to be added to this
$childList .= "<li" . $class . "><a href=\'". get_page_link( $page->ID )."\'>". $page->post_title . "</a>" ;
}
endforeach;
$childList .= \'</ul>\';
endif;
return $childList;
}
// get the absolute top level parent of this page
$topID = get_top_id();
// if no parent, we are ar the top
if(!$topID) $topID = $post->ID;
echo get_sub_pages($topID);
此代码还将类“selected”添加到当前帖子,并将“parent”添加到列表中的当前帖子父级。
希望对别人有帮助!