I have the following WP_Query
arguments:
$posts = new WP_Query(array(
'post__in' => $postids,
'meta_key' =>'ratings_average',
'orderby'=>'meta_value_num',
'order' =>'DESC',
));
$postids is an array of ids which is retrieved from another WP_Query
. My problem here is that even if $postids is empty, WordPress loop shows posts. How can I manage this that it shouldn’t show any post if $postids is empty.
This isn’t directly fixing the issue with
post__in
but I don’t see why this wouldn’t work..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 toWP_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:
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:
This way you will still be able to code against the WP_Query object.
For example:
Just got the same problem, best thing is to check if the array is empty then pass invalid ID to it:
Add that before the query and the problem is solved.
Maybe you have some sticky posts. In this case WordPress will add those posts to your query.
The solution is to set
'ignore_sticky_posts' => 1
. Applying that to your code: