This answer just explains a possible approach and doesn’t provides with detailed code.
The following approach relies more on PHP for filtering the results instead of multiple WP_Query, it uses a single WP_Query along with multiple get_post_meta() calls.
Step 1:
For the current post build an array using get_field() or get_post_meta() with all the necessary key and values:
$current_post = array(
k1 => v1,
k2 => v2,
k3 =>v3
);
Step 2:
Get all the post Ids using WP_Query(meta_query) which has at least one matching key,value pair.
WP_Query[
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'k1',
'value' => 'v1',
'compare' => '='
),
array(
'key' => 'k2',
'value' => 'v2',
'compare' => '='
),
array(
'key' => 'k3',
'value' => 'v3',
'compare' => '='
)
)
]
Step 3:
For all the post ids from above result; iterate and build an array matching_posts with all the key, values;
$matching_posts = array(
post_id_1 => array (
k1 => v1,
k2 => v2,
k3 =>v3
),
post_id_2 => array (
k1 => v1,
k2 => v2,
k3 =>v3
)
.
.
.
);
Step 4:
4.1 :
Use php array functions[array_intersect] to get related post ids for $current_post[];
Remove related post ids from $matching_posts[]
4.2 Remove the last key=>value from $current_post[]; and repeat 4.1
Repeat 4.2
This would give you 3 sets of array:
- Post ids with all key=>value(3) in common,
- and then 2 same key=>value
- And then posts which has only single key=>value in common.
For the other part of question: getting at least n
posts for the current post, you can have a simple query to get n - x
posts which excludes all the post above. Where x is the sum of all matching posts.