WordPress Query: Orderby number of matched rows?

2019-08-11 16:55发布

问题:

My plugin adds a row in the wp_postmeta table whenever a post is liked:

meta_id | post_id | meta_key | meta_value
27526   | 179     | liker    | 177
27527   | 182     | liker    | 343
27528   | 182     | liker    | 360
...

(the meta_value stores the ID of the user which liked this post).

How do I use WP_Query to query all posts, ordered by number of likes?

EDIT: This is how to do it in SQL, but I need the WP_Query equivalent.

SELECT post_id, COUNT(*) AS likes
FROM wp_postmeta
WHERE meta_key='liker'
GROUP BY post_id
ORDER BY likes DESC

回答1:

Check Wordpress Documentation

You could use the parameter orderby: with the string meta_key

<?php

$args = array(
    'post_type' => 'your_post_type',
    'orderby'   => 'meta_value_num',
    'meta_key'  => 'liker',
);
$query = new WP_Query( $args );

?>


回答2:

I've have 3 pages...

ID | post_title
---+------------
6  | Home
65 | Contact   
74 | Blog

And then...

meta_id | post_id | meta_key | meta_value
--------+---------+----------+-----------
403     | 6       | likes    | 100
454     | 65      | likes    | 140
478     | 74      | likes    | 50

If I run...

$args = array(
    'post_type' => 'page',
    'orderby'   => 'meta_value_num',
    'meta_key'  => 'likes',
    'order'     => 'DESC'
);
$query = new WP_Query( $args );

while ( $query->have_posts() ) {
    $query->the_post();
    echo get_the_title() . "<br>";
}

The output is:

Contact
Home
Blog

If I run...

$args = array(
    'post_type' => 'page',
    'orderby'   => 'meta_value_num',
    'meta_key'  => 'likes',
    'order'     => 'ASC'
);
$query = new WP_Query( $args );

while ( $query->have_posts() ) {
    $query->the_post();
    echo get_the_title() . "<br>";
}

The output is:

Blog
Home
Contact


回答3:

I think you may use the SQL...

SELECT post_id, COUNT(*) AS likes
FROM wp_postmeta
WHERE meta_key='liker'
GROUP BY post_id
ORDER BY likes DESC

Only IDs:

$your_ids = wp_list_pluck($your_sql_result, 'ID');

And then query like this:

$args = array(
    'post_status' => 'publish',
    'post__in' => $your_ids,
    'orderby' => 'post__in',
    'post_type' => 'page',
    'posts_per_page' => -1
);
$posts = get_posts($args);