已解决
在 WordPress 5.8.1 中,我有多个作者用户,我正在为每位作者制作一个自定义的评论管理视图。我希望统计每位作者所有文章下的评论数量,于是尝试了如下代码:
function user_nav_counts($views) {
global $current_user, $wp_query;
unset($views['mine']);
unset($views['approved']);
unset($views['moderated']);
unset($views['spam']);
unset($views['trash']);
$author_ID = $current_user->ID;
$types = array(
array('status' => 'approved'),
array('status' => 'moderated'),
array('status' => 'trash')
);
foreach ($types as $type) {
$query = array(
'status' => $type['status'],
'type' => 'comment',
'post_author' => $author_ID,
'post_type' => array('song', 'book'),
'count' => true,
);
$result = new WP_Comment_Query($query);
if ($type['status'] == 'approved'):
$class = ($wp_query->query_vars['comment_approved'] == 'approved') ? ' class="current"' : '';
$views['approved'] = sprintf(__('<a href="/%s"' . $class . '>已批准 <span class="count">(<span class="approved-count">%d</span>)</span></a>', 'approved'), ('wp-admin/edit-comments.php?comment_status=approved'), $result->count);
elseif ($type['status'] == 'moderated'):
$class = ($wp_query->query_vars['comment_moderated'] == 'moderated') ? ' class="current"' : '';
$views['moderated'] = sprintf(__('<a href="/%s"' . $class . '>待审核 <span class="count">(<span class="moderated-count">%d</span>)</span></a>', 'moderated'), ('wp-admin/edit-comments.php?comment_status=moderated'), $result->count);
elseif ($type['status'] == 'trash'):
$class = ($wp_query->query_vars['comment_trash'] == 'trash') ? ' class="current"' : '';
$views['trash'] = sprintf(__('<a href="/%s"' . $class . '>回收站 <span class="count">(<span class="trash-count">%d</span>)</span></a>', 'trash'), ('wp-admin/edit-comments.php?comment_status=trash'), $result->count);
endif;
}
return $views;
}
if (!current_user_can('edit_others_posts')) {
add_filter('views_edit-comments', 'user_nav_counts', 10, 1);
}
使用以上代码,我可以正常生成新的评论导航菜单,但是评论数量 ($result->count
) 总是显示为 0。
即使在 var_dump($result)
中,found_comments
也是 0。
如何正确获取每位作者的评论数量?
@grantchao的方法是正确的,不过你如果坚持需要使用WP_Comment_Query(),你需要把$query中的count改为false,并增加:
‘no_found_rows’ => false, // 必须设置为false
‘number’ => 1, // 必须大于0(防止默认禁用found_rows)
然后使用$total = $comment_query->found_comments;获取符合条件的评论的总数,number 只控制本次查询返回多少条评论数据(例如 1 就只查询1条评论出来),但是 found_comments 是 WP_Comment_Query 内部记录的 符合条件的全部评论总数,跟 number 无关!
@超哥 非常感谢,这就是我想要的效果
如果只要简单的数量,可以直接用
get_comments()
搭配count();
$comments = get_comments([
'status' => 'approve',
'post_author' => $author_ID,
'post_type' => ['song', 'book'],
]);
$total = count($comments);
@grantchao 非常感谢,您的方法确实有效