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?

up vote 19 down vote accepted

I was sure that wp_update_user function should do this (http://codex.wordpress.org/Function_Reference/wp_update_user).

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( array ( 'ID' => $user_id, 'user_login' => $new_login ) ) ;

You have to call custom SQL query to update user_login:

$wpdb->update($wpdb->users, array('user_login' => $new_user_login), array('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.

  • 1
    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. – Mateusz Hajdziony Jun 19 '13 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). – Mateusz Hajdziony Jun 19 '13 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 '13 at 16:19
  • 1
    i needed to add global $wpdb; to make it work – Mauro May 13 '15 at 2:52
  • 2
    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 '16 at 5:09

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.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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