WordPress需求:仅显示登录用户与作者的评论对话
WordPress 评论权限控制实现方案
核心逻辑
- 登录用户仅能查看自己的评论、自己与文章作者的所有回复对话
- 文章作者可查看所有评论及对话
- 未登录用户按原有权限逻辑处理
实现代码
将以下代码添加到主题的functions.php文件中:
function filter_comments_based_on_user($comments_query) { // 仅对非作者的登录用户生效 if (is_user_logged_in() && !current_user_can('edit_post', get_the_ID())) { $current_user_id = get_current_user_id(); $post_author_id = get_post_field('post_author', get_the_ID()); $user_comments_ids = get_comments(array( 'author__in' => array($current_user_id), 'post_id' => get_the_ID(), 'fields' => 'ids' )); // 设置筛选条件:显示当前用户的评论,或作者对当前用户评论的回复 $comments_query->query_vars['meta_query'] = array( 'relation' => 'OR', array( 'key' => 'comment_author_email', 'value' => get_userdata($current_user_id)->user_email, 'compare' => '=' ), array( 'relation' => 'AND', array( 'key' => 'comment_author_email', 'value' => get_userdata($post_author_id)->user_email, 'compare' => '=' ), array( 'key' => 'comment_parent', 'value' => $user_comments_ids, 'compare' => 'IN' ) ) ); } return $comments_query; } add_filter('pre_get_comments', 'filter_comments_based_on_user');
代码说明
- 利用
pre_get_comments钩子拦截评论查询请求 - 先判断当前登录用户是否为文章作者,若非作者则添加筛选规则
- 双条件筛选:要么是当前用户发布的评论,要么是作者针对当前用户评论的回复
- 作者登录时不受任何筛选限制,可查看全部评论内容
可选样式调整
如果需要彻底隐藏其他用户评论的占位区域,可添加以下CSS到主题自定义样式中:
.comment-list .comment:not(.byuser):not(.bypostauthor) { display: none !important; }
注意:修改主题文件前请做好备份,建议使用子主题添加代码,避免主题更新导致代码丢失。
内容的提问来源于stack exchange,提问作者Matei
相关产品推荐
相关产品推荐

