There are a couple of “timing” issues you’re running into here.
When you’re calling wp_get_current_user()
this isn’t really available at the moment of logging in, so to capture the logging-in user, you have to use a slightly different approach.
The same is with logout, as it uses the same method of getting the current user.
In the solution below you’re capturing the logging-in user directly from the wp_login hook, and then instead of calling wp_logout()
, you’re calling the actual functions that do the logging-out for you. And, instead of adding multiple hooks, you’re doing it all within the one hook: wp_login
There’s also a sanity check to ensure the $user
is actually an \WP_User
object, or you’ll get a fatal error on checking the capability.
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 );