WordPress Development Asked by Moa Andersen on October 30, 2021
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.
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:
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";
}
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";
}
Answered by Amin Matola on October 30, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP