0

Having an admin account, I can change everything except the username (which happens to be the login name). I am therefore wondering how to change the username using the functions file.

Running the below as a SQL query works fine, but how do I "convert" it into a function?

add_action('init','username_query');
function username_query() {
    
    global $wpdb;
    $result = (UPDATE `wp_users` SET `user_login`= 'new-admin-name-here' WHERE `user_login`='old-admin-name-here');

}

Any help is appreciated and yes; I know that the user will be logged out and asked to login again.

1 Answer 1

1

There are many ways you can achieve this... In your instance, as you pointed out $wpdb, here is the possible ways you can achieve this:

1. Use $wpdb::query

You can run this query directly using $wpdb's query method as:

add_action("init", "username_query")
function username_query(){
    global $wpdb;

    $prefix  = $wpdb->prefix;

    $query   = "UPDATE `{$prefix}wp_users` SET `user_login`= 'new-admin-name-here' WHERE `user_login`='old-admin-name-here'";

    $results = $wpdb->query( $query );

    if( $results === false ){
        return "Error updating admin";
    }

    return "Admin username updated";
}

2. Use $wpdb::update

You can also use $wpdb's update method to run your query as in below example

add_action("init", "username_query")
function username_query(){
    global $wpdb;

    $updated_rows = $wpdb->update(
                                  "wp_users", 
                                  array( "user_login" => "new_admin_name_here" ), 
                                  array( "user_login" => "old_admin_name_here" ),
                                  array( "%s" ),
                                  array( "%s")
                                );

   if ( $updated_rows === false ){
        return "Error updating admin";
   }

   return "Admin username updated";

}

1
  • some minor mistakes in the code that I were able to fix myself. Thanks for pointing me in the right direction. Commented Jul 21, 2020 at 17:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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