How to change the username with wp-cli?
This does not work:
wp user update old_login --user-login=new_login
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityHow to change the username with wp-cli?
This does not work:
wp user update old_login --user-login=new_login
If we try to change the user login by the email:
wp user update [email protected] --user_login=mary_new
or by the user id:
wp user update 123 --user_login=mary_new
we get the following warning:
User logins can't be changed.
This is the reason:
if ( isset( $assoc_args['user_login'] ) ) {
WP_CLI::warning( "User logins can't be changed." );
unset( $assoc_args['user_login'] );
}
within the user
update
method.
Custom SQL queries:
If we only want to target the wp_users
table and the user_login
field, it's possible to run the SQL query with:
wp db query "UPDATE wp_users SET user_login = 'mary_new' WHERE user_login = 'mary'"
But we have to make sure the user logins are unique.
I experiented with this kind of query:
wp db query "UPDATE wp_users u,
( SELECT
COUNT(*) as number_of_same_login_users
FROM wp_users u
WHERE user_login = 'mary_new'
) tmp
SET u.user_login = 'mary_new'
WHERE
u.user_login = 'mary_old'
AND tmp.number_of_same_login_users = 0"
to enforce the uniqueness of the user_login
field, by only updating, if the no user has the same user login name.
This unrelated answer helped me constructing an UPDATE with a subquery.
Here's the same command in a single line:
wp db query "UPDATE wp_users u, ( SELECT COUNT(*) as number_of_same_login_users FROM wp_users WHERE user_login = 'mary_new' ) tmp SET u.user_login = 'mary_new' WHERE u.user_login = 'mary_old' AND tmp.number_of_same_login_users = 0"
but this is kind of query should be inside a custom command ;-)
Note that the table prefix might be different than wp_
.
Custom WP-CLI commands:
Like explained in the Commands Cookbook, it's possible to create custom WP-CLI commands.
We might try to build a custom command like:
WP_CLI::add_command( 'wpse_replace_user_login', 'WPSE_Replace_User_Login' );
or:
WP_CLI::add_command( 'wpse_user', 'WPSE_User_Command' );
where WPSE_User_Command
extends the User_Command
class. This would need further work.
search-replace
does the trick but can have undesired side effects if old_login
appears in other contexts in the database:
wp search-replace old_login new_login
But before doing that run
wp sql dump
wp search-replace old_login new_login --dry-run
To make an SQL dump and see what is going to be replaced.
--dry-run
to check the extend of the replacements.