How to order a post type with meta_value_num and if meta_value_num does not exist then order by date

You can pass a space-delimited set of columns to orderby argument of WP Query:

$args = array(
    'meta_key' => 'wp_ratings',
    'orderby'  => 'meta_value_num date'
);

$query = new WP_Query( $args );

You can also pass an array of key => sort_order for more granular control, for example:

$args = array(
    'meta_key' => 'wp_ratings',
    'orderby' => array (
                     'meta_value_num' => 'DESC',
                     'date'           => 'ASC'
                 )
);
$query = new WP_Query( $args );

Your actual problem seems to be related with the query and not with the order. As a meta_key has been set, the query will look for some value for that meta key. Because you want get posts with or without that meta key, you need to specify it in the meta_query:

$args = array(
    //meta key for orderby
    'meta_key'   => 'wp_ratings',
    //Meta query set to include when meta_key doesn't exist
    'meta_query' => array(
                        'relation' => 'OR',
                        array(
                            'key'     => 'wp_ratings',
                            'compare' => 'EXISTS'
                        ),
                        array(
                            'key'     => 'wp_ratings',
                            'compare' => 'NOT EXISTS'
                        )
                    ),
    'orderby'    => array (
                     'meta_value_num' => 'DESC',
                     'date'           => 'ASC'
                    )
);
$query = new WP_Query( $args );

Leave a Comment