phpwordpress

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


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.


Solution

  • 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.