这个任务至少需要2个查询,因为它是不规则的。例如
// collect all child posts
$allChildPosts = get_posts([
  \'post_parent__not_in\' => [0],
  \'posts_per_page\' => -1,
]);
// list child posts and filter one post by parent id
$childPosts = [];
foreach ($allChildPosts as $post) {
    $childPosts[$post->post_parent] = $post;
}
// get all parent level posts without descendants
$lonelyPosts = get_posts([
  \'post_parent__not_in\' => array_keys($childPosts),
  \'posts_per_page\' => -1,
]);
$allPosts = array_merge($childPosts, $lonelyPosts);
// As a drawback, you\'d have to sort them manually, since they are glued together
usort($allPosts, \'sorting_function\');
 第一种方法仅使用2个db查询,但在大量发布时效率会很低
第二种方法:
// get all parent posts
$parentPosts = get_posts([
  \'post_parent\' => 0,
  \'posts_per_page\' => -1,
]);
$allPosts = [];
foreach ($parentPosts as $post) {
    $descendants = get_posts([
      \'post_parent\' => $post->ID,
      \'posts_per_page\' => 1,
      \'orderby\' => \'whatever\'
    ]);
    if ($descendants) {
        $allPosts[] = $descendants[0];
    } else {
        $allPosts[] = $post;
    }
}
 第二个更直接,还允许排序后代(否则如何理解哪一个必须是最后一个?),但既然
numberOfParentPosts + 1 查询如果有大量的父帖子,它将变得效率低下。
如果您需要真正高效的解决方案,那么必须手动编写聪明的MySQL。
但请随时证明我错了:)