I have the goal of getting n
custom posts from a query.
I have 4 values stored in ACF.
If I can find n
posts where all these values are the same as the current post's, then I want to return those n
.
If I can only find, for instance, 5 post where the ACF values are the same then I want those and the remaining n-5
to share 3 ACF values, then those sharing 2, then 1 and then just anything if I haven't found n
posts yet.
I've managed to do this, but it seems like a pretty stupid way of doing it.
function queryRelatedMedia($array, $post_id, $postLimit, $genre = null, $rating = null){
$cCount = array_search(end($array), $array);
$cCount = $cCount? $cCount : 0;
$query = new WP_Query(.....); // Some relevant query
while($query -> have_posts() and $cCount < $postLimit){
$query -> the_post();
if($post_id == get_the_id()){ continue; }
if($rating and get_field("rating") != $rating){ continue; }
if($genre and get_field("genre") != $genre){ continue; }
$resArr = array(.....); // Store relevant data in array
if(!array_search($resArr, $array)){
array_push($array, $resArr);
$cCount++;
}
}
}
$queryArray = queryRelatedMedia(array(), $post_id, $amount, $genre, $rating);
$queryArray = queryRelatedMedia($queryArray, $post_id, $amount, $genre);
$queryArray = queryRelatedMedia($queryArray, $post_id, $amount);
So I run the query first with the most specific checks. Then look at how large the array of posts is, if it's not n
then I run it again with 1 parameter less.
Is there a smarter (more efficient) way of doing this?