查询评论超过20条的帖子

时间:2017-03-06 作者:Swen

有没有一种简单的方法可以查询评论数超过某个数字的帖子?

例如,我只想列出评论超过20条的帖子。

$args = array(
    \'post_type\' => \'post\',
    \'post_status\' => \'publish\',

    \'posts_per_page\' => 25,

    // Something like this
    \'comments_query\' => array(
        array(
            \'value\' => 20,
            \'type\' => \'numeric\',
            \'compare\' => \'>=\',
        ),
    )
);

$query = new WP_Query( $args );

1 个回复
最合适的回答,由SO网友:Dave Romsey 整理而成

WP_Query 当前不支持查询comment_count 字段,但有一个建议的此功能修补程序。看见Trac ticket #28399. 更新:#28399已修复,应在版本4.9中发布

同时,这里有一个基于this 将改变where 子句,并允许您根据评论计数限制返回的帖子数量。

将此代码添加到functions.php 或插件:

// Modify the where clause to include only posts with 20 or more comments
function wpse_post_where_comment_count( $where ) {
    // Don\'t fire more than once:
    remove_filter( current_filter(), __FUNCTION__ );

    return "{$where} AND {$GLOBALS[\'wpdb\']->posts}.comment_count >= 20";
}
将此代码添加到模板:

add_filter( \'posts_where\', \'wpse_post_where_comment_count\', 10, 1 );
$query = new WP_Query( [
    \'post_type\'      => \'post\',
    \'post_status\'    => \'publish\',
    \'posts_per_page\' => 25,
] );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) { $query->the_post();
        the_title();
    }
}