这可能比你真正需要的要复杂一点——它包括最上面的帖子(或页面或CPT),并继续列出完整的树。
<?php
// Get the top page in the current tree
$ancestors = $post->ancestors;
// If this page isn\'t the top one in the tree
if($ancestors) {
// The last ancestor is highest in the tree
$topParentID = end($ancestors);
// Use whatever class you want here to differentiate the parent
echo \'<li class="topLevel page_item"><a href="\' . get_the_permalink($topParentID) . \'">\' . get_the_title($topParentID) . \'</a>\';
} else {
$topParentID = $post->ID;
echo \'<li class="topLevel page_item hasChildren current">\' . get_the_title($topParentID);
}
echo \'<ul class="children">\';
wp_list_pages(array(
\'post_type\' => \'your_cpt\',
\'child_of\' => "$topParentID",
\'title_li\' => \'\',
\'post_status\' => \'publish\',
\'sort_column\' => \'post_title\',
\'walker\' => new childNav_walker)
);
echo \'</ul></li>\';
?>
如果您不担心列出完整的树,您可以在类似于上面的wp\\u list\\u pages调用中使用自定义walker,您的walker将为至少有一个子级的每个帖子(或页面或CPT)添加类。
函数的Walker代码。php:
<?php
// childnav walker
class childNav_walker extends Walker_page {
public function start_el(&$output, $page, $depth = 0, $args = array(), $current_page = 0) {
if($depth)
$indent = str_repeat("\\t", $depth);
else
$indent = \'\';
extract($args, EXTR_SKIP);
$css_class = array(\'page_item\');
if(!empty($current_page)) {
$_current_page = get_page( $current_page );
$children = get_children(\'post_type=page&post_status=publish&post_parent=\'.$page->ID);
if(count($children) != 0) {
// this is where you add your custom CSS class,
// change it to whatever you like.
$css_class[] = \'hasChildren\';
}
if(isset($_current_page->ancestors) && in_array($page->ID, (array) $_current_page->ancestors))
$css_class[] = \'current_page_ancestor\';
if($page->ID == $current_page)
$css_class[] = \'current_page_item\';
elseif($_current_page && $page->ID == $_current_page->post_parent)
$css_class[] = \'current_page_parent\';
} elseif($page->ID == get_option(\'page_for_posts\')) {
$css_class[] = \'current_page_parent\';
}
$css_class = implode( \' \', apply_filters( \'page_css_class\', $css_class, $page, $depth, $args, $current_page ) );
if($page->ID == $current_page) {
$output .= $indent .\'<li class="\' . $css_class . \'">\' . $page->post_title;
} else {
$output .= $indent .\'<li class="\' . $css_class . \'"><a href="\' . get_permalink($page->ID) . \'">\' . $page->post_title .\'</a>\';
}
}
}
?>
如上所示,只要在调用中指定帖子类型,就可以使用页面遍历器。