Sort in WP_Query(), not filter? Is it possible?

I want to query and SORT in WP_Query(). But whatever I do, it only prints posts with meta_key set up. But I want all the results and just sort them.

This is my query:

$query = new WP_Query(array(
'post_type' => 'my_post_type',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC'
));

Any ideas how to make sorting happen? It sorts, but only shows posts with meta_key set up. I want all the posts.

2 Answers
2

If you want to sort the posts by the meta post_views_count, and still include posts that do not have that meta, you can use meta_query like so:

'meta_query' => array(
    'relation' => 'OR', // make sure it's OR
    // Include posts that have the meta.
    array(
        'key' => 'post_views_count',
        'compare' => 'EXISTS',
    ),
    // Include posts that don't have the meta.
    array(
        'key' => 'post_views_count',
        'compare' => 'NOT EXISTS',
    ),
),

And you can just use that in place of this:

'meta_key' => 'post_views_count',

I.e. Your code would look like:

$query = new WP_Query(array(
    'post_type'      => 'my_post_type',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_query'     => array(
        'relation' => 'OR',
        array(
            'key'     => 'post_views_count',
            'compare' => 'EXISTS',
        ),
        array(
            'key'     => 'post_views_count',
            'compare' => 'NOT EXISTS',
        ),
    ),
    'orderby'        => 'meta_value_num',
    'order'          => 'DESC',
));

Leave a Comment