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?
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 🙁 :
You have to call custom SQL query to update user_login:
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.
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.
You must use the filter to alter the
$data
when the user is updated, you can not act with the action you would usually hook into a user update.Also you must port several of the security and sanity measures WordPress enacts in its code into your new function.
What you can do:
wp_pre_insert_user_data
filter. Make sure you do that only under correct permissions:add_filter( 'wp_pre_insert_user_data', 'prefix_change_user_login', 10, 4 );
prefix_change_user_login
where you grab the$data
, theuser_login
from the$_POST
and pass it through a number of validation and sanitisation (see https://github.com/WordPress/wordpress-develop/blob/bb27ffce6c3b10738008f9a054782945a0744960/src/wp-includes/user.php#L2076-L2498 for more details)An example of such function:
Now this will allow you to update the user login name, and it will also update the user nicename (used in archives for example)
This of course still requires you to “enable” editing on the WP Admin area, but that shouldn’t be too hard
Note that if any error happens in above code (username exists already, YadaYada) NO error is shown, instead, the user just updates and fallsback to what was prior.
Note that while this code is tested, it is up to you what you do with it, and there are REASONS why wp does not allow to update the user login