Search code examples
phpmetawordpress

Order posts by meta value - wordpress


I have a meta key and value that keeps a track of people that like the post. However if a post has no likes it has no meta key or value. My WP query is thus:

$args = array(
  'post_type' => 'post',
  'meta_key' => '_post_like_count',
  'orderby' => 'meta_value_num',
  'order' => 'DESC',
  'posts_per_page' => 3
);
$pop_posts = new WP_Query( $args );

The query above just doesn't bring back the right results.

I've tried permutations of the $args below but with still no joy:

$args = array(
    'post_type' => 'post',
     'meta_query' => array(
           'relation' => 'OR',
            array(
                    'key' => '_post_like_count',
                    'compare' => 'EXISTS',
                ),
            ),
    'meta_key' => '_post_like_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    posts_per_page' => '3',              
);

Both the $args above bring back results - just not the results of the posts with the most likes.

Can anyone help?


Solution

  • I've spent long time with the meta queries and it usually complicates things.

    My advice would be using direct connection to the database through $wpdb, for being much easier. Take this as a start:

    global $wpdb;
    $posts_with_most_likes = $wpdb->get_results(
                    "
                    SELECT _post_like_count
                    FROM $wpdb->postmeta
                    ORDER BY meta_value_num
                    "
                );