WordPress 5.8.1多作者站点:如何通过WP_Comment_Query在自定义评论视图中获取对应作者的评论总数?
解决WordPress作者评论计数为0的问题
你的问题核心在于WP_Comment_Query并不支持直接使用post_author参数——这个参数是给文章查询(WP_Query)设计的,并非评论查询的合法参数,所以你的查询根本没关联到作者的文章,自然返回0条评论。
下面是修正后的完整方案,我会拆解关键改动点:
核心修正思路
- 先获取当前作者的所有目标类型文章ID(
song和book) - 基于这些文章ID,用WP_Comment_Query统计对应状态的评论数量
- 修复原代码中当前导航状态判断的错误(原代码里的
comment_moderated、comment_trash是错误的查询变量名)
修正后的完整代码
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; // 先获取当前作者的所有song和book类型文章ID(仅取ID,提升查询性能) $author_posts = get_posts(array( 'post_author' => $author_ID, 'post_type' => array('song', 'book'), 'posts_per_page' => -1, 'fields' => 'ids', 'post_status' => 'publish' // 可选:如果只统计已发布文章的评论,可保留此参数 )); // 若作者无相关文章,直接返回空视图(避免后续查询报错) if (empty($author_posts)) { return $views; } $types = array( array('status' => 'approved', 'label' => 'Approved'), array('status' => 'moderated', 'label' => 'Pending'), array('status' => 'trash', 'label' => 'Trash') ); foreach ($types as $type) { // 构建评论查询:限定在作者的文章范围内,筛选对应状态的评论 $query = array( 'status' => $type['status'], 'type' => 'comment', 'post__in' => $author_posts, // 关键:关联作者文章的核心参数 'count' => true, ); $comment_query = new WP_Comment_Query($query); $comment_count = $comment_query->found_comments; // 注意:WP_Comment_Query用found_comments存储计数 // 修复当前状态判断:使用正确的query_vars键名comment_status $current_class = ($wp_query->query_vars['comment_status'] == $type['status']) ? ' class="current"' : ''; // 构建视图链接(用admin_url保证站点URL变化时链接依然有效) $views[$type['status']] = sprintf( __('<a href="%s"' . $current_class . '>%s <span class="count">(<span class="%s-count">%d</span>)</span></a>', 'text-domain'), admin_url('edit-comments.php?comment_status=' . $type['status']), $type['label'], $type['status'], $comment_count ); } return $views; } // 仅对无法编辑他人文章的用户(普通作者)生效 if (!current_user_can('edit_others_posts')) { add_filter('views_edit-comments', 'user_nav_counts', 10, 1); }
关键改动细节
- 获取作者文章ID:用
get_posts精准获取当前作者的目标类型文章ID列表,fields => 'ids'只返回ID,减少数据库查询负载。 - 评论查询关联文章:使用WP_Comment_Query支持的
post__in参数,将评论查询限定在作者的文章范围内。 - 正确获取评论计数:WP_Comment_Query的计数存储在
found_comments属性中,原代码里的$result->count是错误用法。 - 修复当前状态判断:原代码里的
$wp_query->query_vars['comment_moderated']是错误的,正确键名是comment_status,对应值为approved/moderated/trash。 - 使用admin_url函数:替换硬编码的后台链接,适配不同站点的URL配置。
这样修改后,就能正确统计每位作者自己文章的各状态评论数量了。
内容的提问来源于stack exchange,提问作者theKing
相关产品推荐
相关产品推荐

