using wp_query to return posts w/ comment count > 0

I’ve looked at numerous examples of wp_query and can’t figure this out. If the thing I was comparing were a meta value then I could to a meta query, but apparently you can’t do a compare with a non-meta value?

This is what I thought it would work:

Read More
$commentpost = new WP_Query( array( 'key' => 'comment_count',
                                'value' => '0',
                                'compare' => '>',                                                    
                                'orderby' => 'comment_count',
                                'order' => 'DESC', 
                               ) );

Any help would be appreciated.

Related posts

1 comment

  1. 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.

Comments are closed.