The wp_login
hook you are using only triggers when a user login, while we need to trigger function when user changed their role.
The correct for this will be set_user_role
hook.
Please update your code with the given code so User will logout on changing the role.
function logout_pending_users( $user_id, $new_role, $old_roles ) {
// Here we are getting the user object.
$user = get_userdata( $user_id );
// If the user no longer has the 'read' capability or if the new role is 'No role for this site'
if ( ! $user->has_cap( 'read' ) || $new_role === '' ) {
// Here we are logging the user out.
wp_logout();
// Here we are destroying the current session and clear cookies.
wp_destroy_current_session();
wp_clear_auth_cookie();
wp_set_current_user( 0 );
// Here we are redirecting the user to the homepage or any other URL as per our need.
$redirect_url = esc_url( home_url() );
wp_safe_redirect( $redirect_url );
exit;
}
}
add_action( 'set_user_role', 'logout_pending_users', 10, 3 );