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