For example, there are the tags {foo
, bar
, chocolate
, mango
, hammock
, leaf
}
I would like to find all posts with at least 3 of these tags.
A post with tags {foo
, mango
, vannilla
, nuts
, leaf
} will match it because it has {foo
, mango
, leaf
} – so at least 3 tags from the needed set of tags.
Therefore it would be in the list of the matched posts.
Is there a simple way to do that, without doing multiple loops through all the posts ?
The answer below is simplified, and could be extended to check if any posts have 3 matching tags before outputting the list. Using one query and assuming you have at least one post with 3 matching tags:
//List of tag slugs
$tags = array('foo', 'bar', 'chocolate', 'mango', 'hammock', 'leaf');
$args = array(
'tag_slug__in' => $tags
//Add other arguments here
);
// This query contains posts with at least one matching tag
$tagged_posts = new WP_Query($args);
echo '<ul>';
while ( $tagged_posts->have_posts() ) : $tagged_posts->the_post();
// Check each single post for up to 3 matching tags and output <li>
$tag_count = 0;
$tag_min_match = 3;
foreach ( $tags as $tag ) {
if ( has_tag( $tag ) && $tag_count < $tag_min_match ) {
$tag_count ++;
}
}
if ($tag_count == $tag_min_match) {
//Echo list style here
echo '<li><a href="'. get_permalink() .'" title="'. get_the_title() .'">'. get_the_title() .'</a></li>';
}
endwhile;
wp_reset_query();
echo '</ul>';
EDIT: Adjusting the variable $tag_min_match
will set the number of matches.