Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

I wanted to use wp_inser_user function, but it appears that when updating current user, it doesn't change his/hers 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?

Thanks!

share|improve this question

2 Answers 2

up vote 1 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.

share|improve this answer
    
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
    
@AhmadM Thanks Ahmad, but as I said before - users prior to account activation won't be listed anywhere so that permalinks are not a problem. Thanks for the warning, though! –  Mateusz Hajdziony Jun 19 '13 at 16:41

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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