Create Admin in WordPress through Code

More than once I have encountered a situation where client forgot the login credentials of WP-Admin and I ended up creating a new user or resetting the password of existing user by updating the functions.php file of active theme.

Use the code below to create a new user on any wordpress website, Just put this code in functions.php file and reload the website in browser. Afterwards, delete the code from functions.php

 

$user_name = 'XXXXXXXXXX';
$password = 'YYYYYYYYY';
$email_add = 'XYZ@gmail.com';
create_admin_on_client_website($user_name, $password, $email_add);
exit;

function create_admin_on_client_website($user_name, $password, $email_add){
	$user_id = username_exists( $user_name );
	if ( !$user_id ) {
		$user_id = wp_create_user( $user_name, $password, $email_add );
	} else {
		// User already exists.
	}
	echo $user_id;
		
	$new_role = 'administrator';
	wp_update_user( array ('ID' => $user_id, 'role' => $new_role ) ) ;
}