WordPress查询:订单数量匹配的行?

时间:2015-08-02 17:27:19

标签: mysql wordpress

每当收到帖子时,我的插件会在wp_postmeta表格中添加一行:

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

(meta_value存储喜欢此帖子的用户的ID)。

如何使用WP_Query查询所有帖子,按喜欢的数量排序?

编辑:这是在SQL中如何做到这一点,但我需要WP_Query等效。

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

3 个答案:

答案 0 :(得分:0)

Check Wordpress Documentation

您可以使用参数 orderby :字符串 meta_key

<?php

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

?>

答案 1 :(得分:0)

我有3页......

Router.map(function() {
  this.route('users', function () {
    this.route('detail', { path: '/:user_id' });
  });
});

然后......

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

如果我跑......

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

输出结果为:

$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>";
}

如果我跑......

Contact
Home
Blog

输出结果为:

$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>";
}

答案 2 :(得分:0)

我认为您可以使用SQL ...

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

仅ID:

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

然后像这样查询:

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