获取带有父母,孩子和元数据的帖子类型



我想在我的网站主页上显示自定义帖子类型下的所有帖子。这本身很容易做到,但我找不到正确构建它的方法。我想以这种方式显示信息:

Parent Page
- Child Page
[Meta data from above child]
- Child Page
[Meta data from above child]

以下内容接近我需要的,但它只是吐出所有页面,父母和孩子。我需要将它们分组到它们所属的内容下:

<?php
$arr_query_args = array(
'numberposts'  => -1,
'post_type'    => 'tours',
'orderby'   => 'title', 
'order'     => 'ASC',
);
$arr_posts = get_posts( $arr_query_args );
global $post;
foreach( $arr_posts as $this_post ) { ?>
<?php $museum = get_post_meta( $this_post->ID, 'tour_museum', true ); // The museum ?>
<?php $permalink = get_permalink($this_post->ID); // Get the post's permalink ?>
<?php $parent_title = get_the_title($this_post->post_parent); // Post parent title ?>
<?php $parentId = $this_post->post_parent; $linkToParent = get_permalink($parentId); // Post parent URL ?>
<li class="<?php echo $parent_title; ?>">
<a href="<?php echo $linkToParent; ?>"><?php echo $parent_title; ?></a>
<ul class="children">
<li><a href="<?php echo $permalink; ?>"><?php echo $this_post->post_title ?></a></li>
</ul>
<small><?php echo $museum; ?></small>
</li>
<?php } ?>

我已经看了一遍,测试了几件事,但无法获得正确的结构。我不需要父页面或子页面的内容,只需要标题、永久链接和一些元数据。谢谢!

您获取帖子的方式,无论父级是谁,它都会获取所有帖子,因此,为了实现分层显示,您可以使用的解决方案:

  1. 通过在WP_Query函数中设置post_parent => 0来获取顶级父级

例如

$arr_query_args = array(
'numberposts'  => -1,
'post_type'    => 'tours',
'orderby'   => 'title', 
'order'     => 'ASC',
'post_parent'  => 0
);
$parent_posts = get_posts( $arr_query_args );
  1. 然后遍历顶级父级,并通过在函数中设置post_parent => $parent->ID来使用这些父级的 ID 来获取他们的孩子WP_Query

例如

while($parent_posts->have_posts()): $parent_posts->the_post();
$arr_query_args_child = array(
'numberposts'  => -1,
'post_type'    => 'tours',
'orderby'   => 'title', 
'order'     => 'ASC',
'post_parent'  => get_the_ID()
);
$child_posts = get_posts( $arr_query_args_child );
// loop for child post here and fetch meta data etc.
endwhile;
  1. 然后使用孩子的 ID 通过get_post_meta函数获取相关元数据。

使用上述方法,您应该能够实现所需的输出。

最新更新