2

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
  • 1
    You'll need to hook into the posts_orderby filter for that.
    – mrben522
    Commented Apr 8, 2019 at 13:39
  • Ok so as I understand correctly. I now have custom posts in wp_posts table and custom meta in wp_postmeta. Now I only need a way to "connect" those two. So in return it should be something like wp_posts.wp_postmeta DESC? Or how do I connect those two tables? Thanks a lot!
    – LubWn
    Commented Apr 8, 2019 at 13:49

2 Answers 2

6

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',
));
0
1

Have you already tried 'meta_query'? See Order by multiple meta key and meta value [closed]. In your case maybe like so:

$query = new WP_Query([
  'post_type'      => 'my_post_type',
  'post_status'    => 'publish',
  'posts_per_page' => -1,
  'meta_query'     => [
    'relation'         => 'OR',
    'post_views_count' => [
      'key'     => 'post_views_count',
      'compare' => 'EXISTS',
    ],
  ],
  'orderby'        => [
    'post_views_count' => 'DESC',
    'title'            => 'ASC',
  ],
]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.