WordPress的查询:ORDERBY数匹配的行?(WordPress Query: Orderb

2019-10-24 11:13发布

我的插件在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

Answer 1:

检查WordPress的文档

您可以使用参数排序依据 :以字符串meta_key

<?php

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

?>


Answer 2:

我已经有3页...

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

输出是:

Blog
Home
Contact


Answer 3:

我想你可以使用SQL ...

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

只有编号:

$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);


文章来源: WordPress Query: Orderby number of matched rows?