using wp_query to return posts w/ comment count > 0

While the WP_Query class has the native possibility to orderby the comment_count, it doesn’t have the same to query based on those. But when we look at the posts-table, we can see that there isn’t much we need to alter

ID | post_author | post_date | post_date_gmt | post_content | post_title | post_excerpt | post_status | comment_status | ping_status | post_password | post_name | to_ping | pinged | post_modified | post_modified_gmt | post_content_filtered | post_parent | guid | menu_order | post_type | post_mime_type | comment_count

So the thing we could do, is intercept the query and modify the WHERE clause inside the posts_where-filter.

<?php
defined( 'ABSPATH' ) or exit;
/* Plugin Name: (#121083) Query WHERE comment count not is 0 */

add_filter( 'posts_where', 'wpse121083WhereCommentCountNotNull' );
function wpse121083WhereCommentCountNotNull( $where )
{
    // Don't fire more than once:
    remove_filter( current_filter(), __FUNCTION__ );

    # @TODO Add abort clauses/cases here

    return "{$where} AND {$GLOBALS['wpdb']->posts}.comment_count != 0";
}

You still have to fill in the bits like cases where you don’t want to intercept the query. Keep in mind, that it’s not tested.

Leave a Comment