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.
1 Answer
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();