0

I want to compare post tags. If the tags match, then display the matching post. For example, I have a post called "ONE" with some tags and another post called "TWO" with some tags. I want to compare both post's tags and if they match, then display that post.

2
  • Do you mean you want to compare the specific post, or to find a some post with matching tags?
    – Rarst
    Oct 27, 2014 at 13:26
  • i want to compare all the posts with matching tags
    – Jagankumar
    Oct 29, 2014 at 3:53

1 Answer 1

1

Working off the assumption that you're already on Post One, and want to add Post Two below it, as a "Related Posts" type feature, you can use a standard WordPress function to get an array of One's tags, then do a query to grab and display posts with tags that match.

//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();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.