使用Walker和wp_list_pages
时,是否可以将父项及其子项包装在另一个元素中,所以我可以将它们作为一个块来操作?
目前我正在使用代码
class My_Walker extends Walker {
var $db_fields = array(
'parent' => 'post_parent',
'id' => 'ID',
);
public function start_lvl( &$output, $depth = 0, $args = array() ) {
$output .= "<nav class=\"list\">\n";
}
public function end_lvl( &$output, $depth = 0, $args = array() ) {
$output .= "</nav>\n";
}
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$class = 'list-item';
if ( $args['has_children'] ) {
$class ='list-title-item';
}
$output .= "<a href=\"#$item->ID\" class=\"$class\">$item->post_title</a>\n";
}
}
产生
<a href="#116" class="list-title-item">Parent 1</a>
<nav class="list">
<a href="#118" class="list-item">Child 1.1</a>
<a href="#120" class="list-item">Child 1.2</a>
<a href="#122" class="list-item">Child 1.3</a>
</nav>
<a href="#125" class="list-title-item">Parent 2</a>
<nav class="list">
<a href="#127" class="list-item">Child 2.1</a>
<a href="#132" class="list-item">Child 2.2</a>
</nav>
我想得到的是
<div id="title-116" class="list-title">
<a href="#116" class="list-title-item">Parent 1</a>
<nav class="list">
<a href="#118" class="list-item">Child 1.1</a>
<a href="#120" class="list-item">Child 1.2</a>
<a href="#122" class="list-item">Child 1.3</a>
</nav>
</div>
<div id="title-125" class="list-title">
<a href="#125" class="list-title-item">Parent 2</a>
<nav class="list">
<a href="#127" class="list-item">Child 2.1</a>
<a href="#132" class="list-item">Child 2.2</a>
</nav>
</div>
我用代码
调用wp_list_pageswp_list_pages( array(
'child_of' => $page_id,
'post_status' => 'publish',
'order' => 'asc',
'depth' => 2,
'walker' => new My_Walker,
) );
答案 0 :(得分:1)
尝试将<div>
添加到start_el
和end_el
方法,仅适用于顶级项目。 (即深度= 0)
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$class = 'list-item';
if ( $args['has_children'] ) {
$class ='list-title-item';
}
$divopen = '';
if (0 === $depth) {
$divopen = "<div id=\"title-{$item->ID}\" class=\"list-title\">";
}
$output .= "$divopen\r\n<a href=\"#$item->ID\" class=\"$class\">$item->post_title</a>\n";
}
public function end_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
...
// Whatever else output is, plus:
if (0 === $depth) {
$output .= "</div>";
}
}