为了减少垃圾邮件注册,将为用户分配pending 直到他们被审查(此时他们被分配subscriber 角色)。这个pending 角色没有功能。什么时候pending 用户登录后,我想立即将其注销,并将其引导到带有说明的页面。首先,我尝试了以下方法:
function logout_pending_users() {
$current_user = wp_get_current_user() ;
if ( ! $current_user->has_cap( \'read\' ) ) {
$url = \'https://example.com/pending/\' ;
wp_redirect( $url ) ;
wp_logout() ;
exit ;
}
} add_action(\'wp_login\', \'logout_pending_users\') ;
结果:两者
pending 和
subscriber 用户已注销。我试着颠倒
wp_redirect() 和
wp_logout():
$url = \'https://example.com/pending/\' ;
wp_logout() ;
wp_redirect( $url ) ;
exit ;
相同的结果。然后我试着检查角色而不是大写字母(我知道,你不应该…):
function logout_pending_users() {
$current_user = wp_get_current_user() ;
$role = $current_user->roles[0] ;
if ( $role === \'pending\' ) {
$url = \'https://example.com/pending/\' ;
wp_redirect( $url ) ;
wp_logout() ;
exit ;
}
} add_action(\'wp_login\', \'logout_pending_users\') ;
同样的结果。接下来,我根据WP开发者网站上的一个示例尝试了一些东西:
function logout_pending_users() {
$current_user = wp_get_current_user() ;
if ( ! $current_user->has_cap( \'read\' ) ) {
wp_logout() ;
}
} add_action(\'wp_login\', \'logout_pending_users\');
function redirect_pending_users() {
$current_user = wp_get_current_user() ;
if ( ! $current_user->has_cap( \'read\' ) ) {
$url = \'https://example.com/pending/\' ;
wp_redirect( $url ) ;
exit;
} add_action( \'wp_logout()\', \'redirect_pending_users\');
结果:两者
pending 和
subscriber 用户被困在登录页面,URL为:
https://example.com/wp-login.php?redirect_to=https%3A%2F%2Fexample.com%2Fwp-admin%2Fprofile.php&reauth=1在每次尝试中,我都验证了pending 角色没有read 容量(或任何容量),以及subscriber 角色有。我也证实了$current_user->roles[0] 确实包含正确的角色。
我错过了什么?还有别的办法吗?谢谢你的帮助!
最合适的回答,由SO网友:Paul G. 整理而成
有几个;“计时”;您在这里遇到的问题。
当你打电话的时候wp_get_current_user() 这在登录时并不真正可用,因此要捕获登录用户,必须使用稍微不同的方法。
注销也是如此,因为它使用相同的方法获取当前用户。
在下面的解决方案中,您直接从wp\\u登录挂钩捕获登录用户,然后不再调用wp_logout(), 您正在调用为您注销的实际函数。而不是添加多个钩子,而是在一个钩子中完成所有操作:wp_login
还有一个健全的检查,以确保$user 实际上是\\WP_User 对象,否则在检查功能时将出现致命错误。
function logout_pending_users( $username, $user ) {
if ( $user instanceof \\WP_User && !$user->has_cap( \'read\' ) ) {
wp_destroy_current_session();
wp_clear_auth_cookie();
wp_set_current_user( 0 );
wp_redirect( \'https://example.com/pending/\' );
exit;
}
}
add_action( \'wp_login\', \'logout_pending_users\', 100, 2 );