看起来是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();
}
The
wp_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.