Is there a simple way to query posts with a comment count above a certain number?

For example, I want to list only posts that have more than 20 comments.

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

    'posts_per_page' => 25,

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

$query = new WP_Query( $args );

WP_Query does not currently support querying by the comment_count field, but there is a proposed patch for this functionality. See Trac ticket #28399. Update: #28399 has been fixed and should land in version 4.9

In the meantime, here is a workaround based on information from this post which will alter the where clause of a query and allow you to restrict the number of posts returned based on their comment count.

Add this code to your functions.php or to a plugin:

// 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 this code to your template:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.