如何在WordPress中根据访问权限动态移除文章评论功能
功能实现代码补充&修正
你标记的WHAT DO I PUT HERE位置填入以下代码即可实现对应效果:
// 强制修改当前文章的评论状态为关闭 $post_object->comment_status = 'closed'; // 全局过滤评论状态判断结果,适配所有调用comments_open()的场景 add_filter('comments_open', function() { return false; }, 999);
注:如果你的主题存在硬编码评论区的特殊逻辑,可以额外加一行代码移除评论模板加载,进一步确保评论区不输出:
add_filter('comments_template', function() { return __DIR__ . '/empty-comments.php'; }, 999);
现有代码bug修正
你当前写的代码存在两处逻辑错误,需要同步修改避免功能失效:
- 外层权限跳过判断里重复写了两次
!in_array('contributor', $roles),可删除多余的一条 - tier-1权限判断的代码中,
!in_array('tier-2')缺少第二个参数$roles,需要修改为!in_array('tier-2', $roles),否则会出现PHP警告且权限判断逻辑错误
完整可运行代码
add_action( 'the_post', 'pp_disable_comments' ); function pp_disable_comments($post_object) { // only run if single page if (is_single()) { $pp_disable_comments = false; $user = wp_get_current_user(); $roles = (array) $user->roles; // skip if user is contributor/author/editor/administrator OR if the post is public if ((!in_array('contributor', $roles) && !in_array('author', $roles) && !in_array('editor', $roles) && !in_array('administrator', $roles)) || has_term('public', 'access-control')) { // run if post is tier-0 only if (has_term('tier-0', 'access-control')) { // check if user not in allowed roles if (!in_array('tier-0', $roles) && !in_array('tier-1', $roles) && !in_array('tier-2', $roles)) { $pp_disable_comments = true; } } // run if post is tier-1 only if (has_term('tier-1', 'access-control')) { // check if user not in allowed roles if (!in_array('tier-1', $roles) && !in_array('tier-2', $roles)) { $pp_disable_comments = true; } } // run if post is tier-2 only if (has_term('tier-2', 'access-control')) { // check if user not in allowed roles if (!in_array('tier-2', $roles)) { $pp_disable_comments = true; } } } // disable comments if required if ($pp_disable_comments == true) { // 强制修改当前文章的评论状态为关闭 $post_object->comment_status = 'closed'; // 全局过滤评论状态判断结果,适配所有调用comments_open()的场景 add_filter('comments_open', function() { return false; }, 999); } } }
内容的提问来源于stack exchange,提问作者Aaron McKeon
相关产品推荐
相关产品推荐

