How to change user_login with wp-cli?

Not allowed by design:

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.

Possible workarounds:

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.

Leave a Comment