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:
EDIT: Adjusting the variable
$tag_min_match
will set the number of matches.Here’s one way to do it:
Given a set of 5 tags,
{a, b, c, d, e}
:1) In PHP, generate all the possible subsets containing 3 elements, without repetition:
2) Convert those subsets into a massive taxonomy query:
The approach of sprclldr is the one I used. As for the while loop, here is what I used instead :
I then take the top posts :
my_array_column
is a similar function than the PHP 5,5’s array_column :It doesn’t answer the initial question (but it resolves my root problem), as
: if there is no related posts with 3 common tags, then this will all the same give some posts.