phpwordpressadd-filter

Only return posts with comments in Wordpress


I'm surprised I cannot find much on this topic, perhaps I'm confused.

I am creating an archive page of comments. I want to get all posts with comments where I will list the post title followed by the all the comments for that post underneath using wp_list_comments or WP Comment Query.

My question is how can I filter WP_Query() so I can only return posts that have comments.

I've tried to modify this approach list posts with no comments - postpostmodern's answer but I want to do the exact opposite.

Here is the function:

function filter_comment_count( $sql ){
    global $wpdb;
    $comment_count = get_query_var( 'comment_count' );

    if( is_numeric($comment_count) )
        $sql .= $wpdb->prepare( " AND {$wpdb->posts}.comment_count != %d ", $comment_count);

    return $sql;
    }
add_filter( 'posts_where', 'filter_comment_count'  );

And then I'm attempting to use it in my loop, here is an excerpt:

$args = array (
    'comment_count'  => '0'
    'pagination'     => true,
    'posts_per_page' => '10',
);

$the_query = new WP_Query($args); 
    while($the_query->have_posts()) : $the_query->the_post();  
        get_template_part( 'content', get_post_format() );
    endwhile;
wp_reset_postdata();

I guess the bit that is tripping me up is AND {$wpdb->posts}.comment_count != %d I want it to return comment_count not equal to 0 or whatever allows me to get only posts with comments in my WP_Query($args);

Also I'm not sure where to put remove_filter( 'posts_where', 'filter_comment_count' );?

I realise there is 'orderby' => 'comment_count' but that doesn't exactly help my situation as far as I understand.


Solution

  • Might not give the exact results you want, nor be efficient, but this is all I can think of:

    Inside your loop, add:

    $comments = get_comments(array('post_id' => $post->ID));
    if ($comments !== '' && !empty($comments)) {
    // The rest.
    }
    

    And that should output only the posts that have comments associated with them.

    Edit:

    There's also

        if( 0 < $post->comment_count ){
    
            // Output
    
        }
    

    Which I retrieved from here: https://wordpress.stackexchange.com/questions/125577/only-display-posts-with-comments