我已经在管理面板设置->讨论部分标记了选项-“用户必须注册并登录才能发表评论”,但我希望只有订阅者角色用户才能发表评论,其他角色类型的用户不能发表评论。
谢谢
我已经在管理面板设置->讨论部分标记了选项-“用户必须注册并登录才能发表评论”,但我希望只有订阅者角色用户才能发表评论,其他角色类型的用户不能发表评论。
谢谢
我建议在加载注释表单的主题文件中添加一个片段,检查是否有登录用户,如果该用户是订阅者,则向他们显示注释表单。下面的例子使用了216主题:
在注释中。php:
// First, get the current user and check their role
$user = wp_get_current_user();
if ( in_array( \'subscriber\', (array) $user->roles ) ) {
// The current user has the subscriber role, show the form
comment_form( array(
\'title_reply_before\' => \'<h2 id="reply-title" class="comment-reply-title">\',
\'title_reply_after\' => \'</h2>\',
) );
}
这样,只有具有订阅者角色的用户才能看到注释表单。看起来是core第一次调用wp_get_current_user()
在WP::init()
方法
为了更好地理解上下文,我们看到它就在after_setup_theme
钩子,就在init
挂钩src:
do_action( \'after_setup_theme\' );
// Set up current user.
$GLOBALS[\'wp\']->init();
do_action( \'init\' );
在哪里WP::init()
定义为src:public function init() {
wp_get_current_user();
}
Thewp_get_current_user()
是的包装器_wp_get_current_user()
包含对的调用wp_set_current_user()
以各种方式,例如wp_set_current_user(0)
对于已注销的用户。这里有一个建议set_current_user
在wp_set_current_user()
:
/**
* Comments only open for users with the \'subscriber\' role
*/
add_action( \'set_current_user\', function() use ( &$current_user )
{
if( $current_user instanceof \\WP_User
&& $current_user->exists()
&& in_array( \'subscriber\', (array) $current_user->roles, true )
)
return;
add_filter( \'comments_open\', \'__return_false\' );
} );
如果当前用户具有订阅方角色,则不执行任何操作。对于所有其他用户或访问者,评论将被强制关闭。我可能过于谨慎地检查\\WP_User
对象实例,但我还是保留了它,因为它可能会$current_user
, 与WordPress中的许多其他内容一样;-)
使用的原因$current_user
在这里,而不是打电话wp_get_current_user()
, 是为了避免可能的无限循环,但如果需要的话,有一些方法可以处理。这也很吸引人determine_current_user
滤器
对于访客(未登录)wp_get_current_user()
将返回\\WP_User
ID为的对象0
和角色作为空数组。那是因为wp_set_current_user(0)
前面提到的电话。
在这里$current_user->exists()
是的包装器! empty( $current_user->ID)
.
我同意@TammyShipps关于角色数组转换的观点,但正如@cybmeta所指出的,仅隐藏评论表单不会阻止其他用户进行评论。
另一种方法是对我最近的答案稍加改写here:
/**
* Comments only open for users with the \'subscriber\' role
*/
add_action( \'init\', function()
{
$u = wp_get_current_user();
if( $u->exists() && in_array( \'subscriber\', (array) $u->roles, true ) )
return;
add_filter( \'comments_open\', \'__return_false\' );
} );
这两种方法都应停止向wp-comments-post.php
文件,因为comments_open()
在那里检查。我还没有检查,但我认为它也可以用于xml rpc。我们也可以试试pre_comment_on_post
钩住以停止注释处理,例如抛出\\WP_Error
.
下面的代码检查如果用户不是订阅者,则不会显示注释表单。评论表单仅在用户登录且用户角色为订阅方时显示。
add_filter( \'init\', \'manage_comment\');
function manage_comment()
{
global $current_user;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
if ($user_role!=\'subscriber\')
{
add_filter( \'comments_open\', \'__return_false\' );
}
}
评论。php <?php $args=array( \'type\'=> \'comment\', \'callback\'=>\'my_comment_list\', ); ?> <ol class=\"comments-list\"> <?php wp_list_comments($args) ?>