当一个页面有孩子时,我想在列表中添加一个ul,我会对所有post\\u类型进行foreach,所以我不认为我可以使用wp_list_pages. 我一直在尝试解决这个问题,但刚刚以以下内容结束upp:
// Check for children
$children = array();
foreach ( $values as $post ) {
if( $post->post_parent ) {
$children[] = $post->ID;
}
}
foreach ( $values as $post ) {
setup_postdata( $post );
if( in_array( $post->ID, $children ) ) {
$output .= \'<ul>\';
$output .= \'<li data-id="\'. $post->ID .\'" data-area="\'. $area[\'area\'] .\'"><p>\'. get_the_title() .\'</p><span>\'. __(\'Child\', \'blocks\') .\'</span></li>\';
$output .= \'</ul>\';
} else {
$output .= \'<li data-id="\'. $post->ID .\'" data-area="\'. $area[\'area\'] .\'"><p>\'. get_the_title() .\'</p><span>\'. __(\'Parent\', \'blocks\') .\'</span></li>\';
}
wp_reset_postdata();
}
最合适的回答,由SO网友:Mridul Aggarwal 整理而成
//first let\'s separate all the top level pages & child pages
$top_lvl = array();
$children = array();
foreach ( $values as $post ) {
if( $post->post_parent ) {
$children[$post->post_parent][] = $post;
} else {
$top_lvl[] = $post;
}
}
//now we have all top level pages in $top_lvl
//& we can access their child pages at $children[<top_lvl_ID>]
//now lets loop through top_lvl pages & display them
foreach ( $top_lvl as $post ) {
setup_postdata( $post );
$output .= \'<li data-id="\'. $post->ID .\'" data-area="\'. $area[\'area\'] .\'"><p>\'. get_the_title() .\'</p><span>\'. __(\'Parent\', \'blocks\') .\'</span></li>\';
//check if this post has children
if( isset( $children[$post->ID] ) ) {
foreach( $children[$post->ID] as $post ) {
//do something with children here
}
}
}
//can\'t forget to reset the global data
wp_reset_postdata();