显示与自定义帖子标题相同的标签



我不知道。在我的{custom-post-type}.php中,我想创建一个循环,首先显示页面的标题和内容。然后,它还生成一个列表,其中包含与页面标题同名的标签的所有内容。

有人能在路上帮我一下吗?

需要一个WP_Query实例来查询与标题同名的分类法术语内的帖子。这可以通过将tax_query字段添加到参数中来完成。

<?php
// WordPress header
get_header();
the_post();
$args = array(
'post_type' => 'custom-post-type',
'posts_per_page' => -1, // -1 retrieves all the posts the query finds.
'tax_query' => array(
array(
'taxonomy' => 'category', // This is the default 'post' taxonomy, if you are using a custom taxonomy then you need to change this.
'field'    => 'name', // Use name as you want to match the title
'terms'    => get_the_title(), // Get the title of the current post as a string.
)
),
);
$query = new WP_Query($args);
if($query->have_posts()):
while($query->have_posts()): $query->the_post(); // Loop through the posts from the term with same name as current post title. ?>
<article class="post">
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
</article>
<?php endwhile;
wp_reset_postdata(); // Reset usage of 'the_post()'
endif;
<?php get_footer();

最新更新