18

As in the title, how to programatically change user's login?

I wanted to use wp_insert_user function, but it appears that when updating current user, it doesn't change their username. Should I use $wpdb->update for that? If yes, how would code for changing username look like? What consequences would changing user login have, given that WordPress API doesn't allow changing usernames?

2 Answers 2

27

I was sure that wp_update_user() should do this.

It even gets user_login as param, but it looks like it ignores it, when you set this param.

So this code looks OK, but it doesn't work as you wish it did :( :

wp_update_user(
    ['ID' => $user_id, 'user_login' => $new_login] 
);

You have to call custom SQL query to update user_login:

global $wpdb;
$wpdb->update(
    $wpdb->users, 
    ['user_login' => $new_user_login], 
    ['ID' => $user_id]
);

It works OK and I don't think it has any serious consequences, because WP uses users ID to assign posts/comments (and so on) to user.

The only problem I can think of is that when this user is currently logged in, he will be logged out after user_login change.

8
  • 3
    Not really, check the notes for this function (as well as the code): Please note that we cannot change the usernames through this function, in fact the usernames cannot be changed from the admin dashboard as well since WordPress does not allow the usernames to be updated. Jun 19, 2013 at 15:13
  • Thanks, that works great! No worries about logged in users, though, as I only allow username change for logged out users (account activation via e-mail). Jun 19, 2013 at 15:40
  • @pogoking One thing you might want to consider is that user or author permalinks might be broken after enabling users to change their usernames if pretty permalinks are enabled, so you might need to make measures to compensate for that.
    – Ahmad M
    Jun 19, 2013 at 16:19
  • 2
    i needed to add global $wpdb; to make it work
    – Mau
    May 13, 2015 at 2:52
  • 4
    Old post, but im looking at doing this myself, it would be worth checking there isnt another user with the same user_login registered on your site as the login form obviously uses this value to find accounts and match password hashes
    – haxxxton
    May 24, 2016 at 5:09
7

You might consider changing the user_nicename as well via the SQL query. Once this is done, all permalinks and other functions will work perfect.

1
  • Instead you might consider using an ID based profile slug instead of a nice_name one. It will ensure that the profile will have a universal url and you won't have random 404 pages popping up (I guess that's better for SEO). Mar 27, 2021 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.