douluan4644 2014-08-20 09:47
浏览 34
已采纳

仅返回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.

  • 写回答

1条回答 默认 最新

  • duannuci4008 2014-08-20 15:10
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制