How to auto login user again after change user_login

I have a system work by ajax that is change user_login of users and this is my code:

$wpdb->update($wpdb->users, array('user_login' => sanitize_text_field($args['user_login'])), array('ID' => $user_id));

After user_login is changed WordPress is log out this user so I try to use wp_signon after user_login changed but it’s not working, Any advice?

1 Answer
1

I found when attempting similar I needed to clear the user cache to get the relogin to work (after much frustrating testing!):

wp_cache_delete($user_id, 'users');
wp_cache_delete($old_user_login, 'userlogins'); // maybe unnecessary?
$creds = array('user_login' => $user_login, 'user_password' => $user_password, 'remember' => true);
wp_signon($creds);

Note for this to work you may also need the user to change their password at the same time so that you can populate the $user_password field with a plain text password to provide to wp_signon

Leave a Comment