Victor Sokoliuk
Victor Sokoliuk

Reputation: 445

When sorting posts by post meta in WP_Query, only posts with a meta value are returned

I need to sort posts by rating. And this code does the job well:

<?php
    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
    $args = array (
    'post_type' => 'brands',
    'posts_per_page' => 6,
    'meta_key' => 'post_average_rating',
    'orderby'  => 'meta_value_num',
    'order'    => 'DESC',
    'paged' => $paged
    );

    $brands = new WP_Query( $args );
?>

But there is a problem. If a post does not have a rating value, it simply does not appear. As you can see, I need six posts to be displayed on the page. But if all posts have a rating in only three, only three will be displayed. And I would like to display post without a rating also. Please tell me how this can be solved?

Upvotes: 1

Views: 63

Answers (1)

Victor Sokoliuk
Victor Sokoliuk

Reputation: 445

thanks FluffyKitten's comment the solution was found. Here is the code:

<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array (
    'post_type' => 'brands',
    'posts_per_page' => 6,
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'meta_query' => array(
        'relation' => 'OR',
        array(
           'key'=>'post_average_rating',
           'compare' => 'EXISTS'         
        ),
        array(
            'key'=>'post_average_rating',
            'compare' => 'NOT EXISTS'         
        )
    ),
   'paged' => $paged
);

$brands = new WP_Query( $args );
?>

Posts with a rating are now displayed first, sorted from highest to lowest, and posts that have no rating are just displayed after them.

Reference: Orderby meta value only returns posts that have existing meta key on wordpress.stackexchange.com

Upvotes: 2

Related Questions