How to compare post tags?

时间:2014-10-27 作者:Jagankumar

我想比较post标签。如果标签匹配,则显示匹配的帖子。例如,我有一篇名为“一”的帖子,上面有一些标签,还有一篇名为“二”的帖子,上面有一些标签。我想比较两个帖子的标签,如果它们匹配,那么显示该帖子。

1 个回复
最合适的回答,由SO网友:DanBeckett 整理而成

假设你已经写了一篇文章,并且想在下面添加第二篇文章,作为“相关文章”类型的功能,你可以使用标准的WordPress函数获取一个标签数组,然后进行查询以获取和显示标签匹配的文章。

//get just the IDs of Post One\'s tags
$tag_ids = wp_get_post_tags($post->ID, array(\'fields\' => \'ids\'));

//perform a query looking up any posts that have all the same tags.
//note: \'tag__and\' will look for posts with ALL the tags, you can replace
//this with \'tag__in\' if you want a less strict search to find ANY of the tags. 
$tag_query = new WP_Query( array( \'tag__and\' => $tag_ids ) );

//standard loop fare to display posts that are found
if($tag_query->have_posts()) : while($tag_query->have_posts()) : $tag_query->the_post(); ?>
    <div class="related_post">
        <h3><?php echo get_the_title(); ?></h3>
        <?php the_content(); ?>
    </div>
<?php endwhile; endif;

//reinstate original WordPress query
wp_reset_query();

结束