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

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