Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is WordPress showing query results from an empty post__in array?

Tags:

php

wordpress

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.

like image 922
user48752 Avatar asked Apr 23 '14 14:04

user48752


1 Answers

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.

like image 97
celeriko Avatar answered Oct 21 '22 11:10

celeriko