First of all, you have a typo in your code. The variable with post IDs is called post_id_array
, but your foreach loop uses post_ids_array
(ids instead of id).
When you fix this, then there’s one more problem. Meta query param should be an array of queries and each query should be an array. But your $post_args
generated by your code looks like this:
array(4) {
["post_type"]=>
string(4) "post"
["posts_per_page"]=>
int(3)
["post_status"]=>
string(7) "publish"
["meta_query"]=>
array(1) {
[0]=>
array(2) {
[0]=>
array(3) {
["key"]=>
string(17) "relate_blog_posts"
["value"]=>
string(2) "12"
["compare"]=>
string(4) "LIKE"
}
[1]=>
array(3) {
["key"]=>
string(17) "relate_blog_posts"
["value"]=>
string(2) "24"
["compare"]=>
string(4) "LIKE"
}
}
}
}
As you can see, meta_query
is an array containing an array containing queries.
And here is your code with all the fixes:
$post_ids_array = array( "12", "24" ); //this array will be dynamically generated
$meta_array = array();
foreach ($post_ids_array as $key => $value) {
array_push($meta_array,
array(
'key' => 'relate_blog_posts',
'value' => $value,
'compare' => 'LIKE'
)
);
}
$post_args = array(
'post_type' => 'post',
'posts_per_page' => 3,
'post_status' => 'publish',
'meta_query' => $meta_array
);
$post_query = new WP_Query($post_args);