【问题标题】:Only return posts with comments in Wordpress仅在 Wordpress 中返回带有评论的帖子
【发布时间】:2014-10-13 15:03:34
【问题描述】:

我很惊讶我在这个话题上找不到太多,也许我很困惑。

我正在创建 cmets 的存档页面。我想获取所有带有 cmets 的帖子,我将在其中列出帖子标题,然后使用 wp_list_cmets 或 WP Comment Query 在下面列出该帖子的所有 cmets。

我的问题是如何过滤 WP_Query() 以便我只能返回包含 cmets 的帖子。

我试图修改这种方法 list posts with no comments - 后现代的回答,但我想做完全相反的事情。

函数如下:

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'  );

然后我试图在我的循环中使用它,这里是一个摘录:

$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();

我猜是 AND {$wpdb->posts}.comment_count != %d 我希望它返回不等于 0 的 comment_count 或任何允许我在我的 WP_Query($args); 中仅获得带有 cmets 的帖子

我也不知道把remove_filter( 'posts_where', 'filter_comment_count' );放在哪里?

我知道有'orderby' => 'comment_count',但据我所知,这并不能完全帮助我的情况。

【问题讨论】:

    标签: php wordpress add-filter


    【解决方案1】:

    老问题,但如果有人像我一样偶然发现这个问题,WordPress 4.9 将“comment_count”参数添加到 WP_Query。

    该值可以是您需要的 cmets 数量的整数,也可以是一个数组,其中第一个参数是“值”,第二个参数是“比较”搜索运算符。

    只返回带有 cmets 的帖子:

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

    https://developer.wordpress.org/reference/classes/wp_query/#comment-parameters

    【讨论】:

      【解决方案2】:

      可能无法给出你想要的确切结果,也没有效率,但这是我能想到的:

      在你的循环中,添加:

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

      这应该只输出与他们关联的 cmets 的帖子。

      编辑:

      还有

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

      我从这里检索到的内容: https://wordpress.stackexchange.com/questions/125577/only-display-posts-with-comments

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-10
        • 2011-06-17
        • 1970-01-01
        • 2019-09-24
        • 1970-01-01
        • 2015-05-24
        • 2019-06-13
        • 1970-01-01
        相关资源
        最近更新 更多