首先,为什么要通过自定义查询查询帖子?我们有WP_Query
类别和get_posts
函数来执行此操作。
$child_pages = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_parent = ".$post->ID." AND post_type = \'page\' ORDER BY menu_order", \'OBJECT\');
成为
$pages = get_posts(array(
\'post_type\' => \'page\',
\'orderby\' => \'menu_order\'
\'order\' => \'ASC\'
\'posts_per_page\' => -1,
));
接下来,您应该使用
get_page_children
功能(
get_page_children on codex) 生成树列表。
get_page_children
每次我们要生成子项列表时,都不会查询数据库,而是使用存储在中的所有帖子的列表
$pages
变量
<ul>
<?php foreach ($pages as $page): ?>
<?php if ($page->post_parent == 0): ?>
<li>
<?php echo $page->post_title; ?>
<?php $children = get_page_children($page->ID, $pages); ?>
<ul>
<?php foreach ($children as $child): ?>
<?php if ($child->post_parent == $page->ID): ?>
<li>
<?php echo $child->post_title; ?>
<?php $granchildren = get_page_children($child->ID, $pages); ?>
<ul>
<?php foreach ($granchildren as $grandchild): ?>
<li><?php echo $grandchild->post_title; ?></li>
<?php endforeach; ?>
</ul>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</li>
<?php endif; ?>
<?php endforeach ?>
</ul>
编辑。我认为这符合您现在的期望:
<?php $posts = get_posts(array(\'posts_per_page\' => -1, \'post_type\' => \'page\')); ?>
<?php $children = get_page_children($post->ID, $posts); ?>
<?php foreach ($children as $child): ?>
<?php if ($child->post_parent == $post->ID): ?>
<div>
<h2><?php echo $child->post_title; ?></h2>
<ul>
<?php $grandchildren = get_page_children($child->ID, $posts); ?>
<?php foreach ($grandchildren as $grandchild): ?>
<li><?php echo $grandchild->post_title; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<?php endforeach; ?>