To reduce spam registrations, users are assigned the pending
role until they're vetted (at which point they're assigned the subscriber
role). The pending
role has no capabilities. When pending
users log in, I want to log them out immediately and direct them to a page with an explanation. First, I tried the following:
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') ;
Result: both pending
and subscriber
users are logged out. I tried inverting the order of wp_redirect()
and wp_logout()
:
$url = 'https://example.com/pending/' ;
wp_logout() ;
wp_redirect( $url ) ;
exit ;
Same result. Then I tried checking roles instead of caps (I know, you shouldn't...):
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') ;
Again, same result. Next, I tried something based on an example on the WP Developer site:
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');
Result: both pending
and subscriber
users are stuck at the login page, with URL:
https://example.com/wp-login.php?redirect_to=https%3A%2F%2Fexample.com%2Fwp-admin%2Fprofile.php&reauth=1
During each attempt, I verified that the pending
role has no read
capacity (or any capacity), and that the subscriber
role does. I also verified that $current_user->roles[0]
does, indeed, contain the correct role.
What am I missing? Is there another way? Thank you for any help!