Php 仅在Wordpress中返回带有评论的帖子
我很惊讶我在这个话题上找不到太多东西,也许我有点困惑 我正在创建一个包含评论的归档页面。我想获得所有带有评论的帖子,我将使用wp_list_comments或wp Comment查询列出帖子标题,然后在下面列出该帖子的所有评论 我的问题是如何过滤WP_Query(),以便只返回有评论的帖子 我试图修改这种方法——postpostmodern的答案,但我想做完全相反的事情 以下是函数:Php 仅在Wordpress中返回带有评论的帖子,php,wordpress,add-filter,Php,Wordpress,Add Filter,我很惊讶我在这个话题上找不到太多东西,也许我有点困惑 我正在创建一个包含评论的归档页面。我想获得所有带有评论的帖子,我将使用wp_list_comments或wp Comment查询列出帖子标题,然后在下面列出该帖子的所有评论 我的问题是如何过滤WP_Query(),以便只返回有评论的帖子 我试图修改这种方法——postpostmodern的答案,但我想做完全相反的事情 以下是函数: function filter_comment_count( $sql ){ global $wpdb;
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();
我想让我绊倒的是和{$wpdb->posts}。comment\u count!=%d
我希望它返回comment\u count
不等于0或任何允许我在WP\u查询($args)中仅获取带有注释的帖子的内容代码>
此外,我也不确定在哪里放置remove_filter('posts_where','filter_comment_count')代码>
我意识到存在“orderby”=>“comment\u count”
,但据我所知,这对我的情况并没有帮助。可能无法给出您想要的确切结果,也可能效率不高,但这是我所能想到的:
在循环中,添加:
$comments = get_comments(array('post_id' => $post->ID));
if ($comments !== '' && !empty($comments)) {
// The rest.
}
这应该只输出有相关评论的帖子
编辑:
还有
if( 0 < $post->comment_count ){
// Output
}
if(0<$post->comment\u count){
//输出
}
我从这里检索到:
这是一个老问题,但如果有人像我一样偶然发现这个问题,WordPress 4.9会在WP\u查询中添加“comment\u count”参数
该值可以是所需注释数的整数,也可以是第一个参数为“value”,第二个参数为“compare”搜索运算符的数组
要仅返回带有注释的帖子,请执行以下操作:
$args = array(
'comment_count' => array(
'value' => 0,
'compare' => '>',
),
'pagination' => true,
'posts_per_page' => 10,
);
$the_query = WP_Query( $args );
看