Wordpress query showing post in empty post__in array?
This isn't directly fixing the issue with post__in
but I don't see why this wouldn't work..
if(!empty($postids)){
$posts = new WP_Query(array(
'post__in' => $postids,
'meta_key' =>'ratings_average',
'orderby'=>'meta_value_num',
'order' =>'DESC',
));
} else {
//Do something else or nothing at all..
}
as you can see the WP_Query
call will only happen if $postids
has value/s in it. if it doesn't, then no call is made to WP_Query
and the loop will just never happen, same as if your query returned 0 posts.
As noted, wp devs don't want to fix this. Having said that, you could pass a non-empty array of invalid IDs, like this:
if(empty($postids)) {
$postids = ['issue#28099'];
}
$posts = new WP_Query(array(
'post__in' => $postids,
'meta_key' =>'ratings_average',
'orderby'=>'meta_value_num',
'order' =>'DESC',
));
Bad practice you say ? Yeah, I am not sure from whose side though ...
To keep the flow correct with the WP_Query. Use it like this:
$postIdArray = array(
1, 2, 3
);
$queryArgs = array(
'post_type' => 'any',
'post_status' => 'published',
'post__in' => ((!isset($postIdArray) || empty($postIdArray)) ? array(-1) : $postIdArray)
);
This way you will still be able to code against the WP_Query object.
For example:
$postIdArray = array(
1, 2, 3
);
$queryArgs = array(
'post_type' => 'any',
'post_status' => 'published',
'post__in' => ((!isset($postIdArray) || empty($postIdArray)) ? array(-1) : $postIdArray)
);
$postQuery = new \WP_Query($queryArgs);
$postCount = $postQuery->post_count;
$totalCount = $postQuery->found_posts;