1

I am using the Like/Dislike plugin on a custom post type and am trying to order the display of posts by the most like count down to those that have no likes (and no set meta value in the posts meta table).

My current query is the following:

$args = array(  
    'post_type' => 'idea',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'meta_key' => 'pld_like_count',
    'orderby' => 'meta_value_num title',
    'order' => 'DESC'
  );

This displays only the posts that have a defined meta_key and meta_value for the Like/Dislike plugin.

Is there a way to order posts from the most likes down to those without the defined meta_key/value?

Posts without a set like meta_key/value still need to be displayed because users need to be able to like the posts with the button.

1
  • Note that it's not recommended to set posts_per_page to -1, and instead, use a fixed number that the database can handle at once.
    – Sally CJ
    Commented Apr 15, 2023 at 2:30

1 Answer 1

0

Yes, there is — use a meta_query with 2 clauses, one which selects posts having the meta, and the second clause with a 'compare' => 'NOT EXISTS' which selects posts without that meta.

So in your $args array, just replace the 'meta_key' => 'pld_like_count' with this one:

'meta_query' => array(
    // make sure it's OR
    'relation' => 'OR',

    array( // selects posts having the meta
        'key'  => 'pld_like_count',
        'type' => 'NUMERIC',
    ),

    array( // selects posts without the meta
        'key'     => 'pld_like_count',
        'compare' => 'NOT EXISTS',
    ),
),
2
  • Thanks for this detailed solution. I just needed to add 'orderby' => 'meta_value_num title' to the $args to get to it working. Commented Apr 19, 2023 at 19:42
  • In that case, I rolled back my answer to the original version. Cheers :)
    – Sally CJ
    Commented Apr 21, 2023 at 15:49

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.