我想在我的网站主页上显示自定义帖子类型下的所有帖子。这本身很容易做到,但我找不到正确构建它的方法。我想以这种方式显示信息:
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 } ?>
我已经看了一遍,测试了几件事,但无法获得正确的结构。我不需要父页面或子页面的内容,只需要标题、永久链接和一些元数据。谢谢!
您获取帖子的方式,无论父级是谁,它都会获取所有帖子,因此,为了实现分层显示,您可以使用的解决方案:
- 通过在
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 );
- 然后遍历顶级父级,并通过在函数中设置
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;
- 然后使用孩子的 ID 通过
get_post_meta
函数获取相关元数据。
使用上述方法,您应该能够实现所需的输出。