Sometimes you may forget your username or email address on a WordPress site and cannot login to the admin area of the website.
Some users may get their site hacked and admin account deleted. In that case, adding an admin user via functions.php can quickly restore your access to the WordPress admin area.
One way to do this is by adding an admin user to the WordPress database using MySQL. But you may be unable to connect to phpMyAdmin or don’t want to run MySQL queries directly.
Having said that, let’s see how you can easily add an admin user in WordPress via functions.php (using FTP access).
Adding an Admin User in WordPress via function.php (Using FTP)
Now you need to add this code at the bottom of theme’s functions.php.
function yp_admin_account(){
$user = 'Username';
$pass = 'Password';
$email = 'email@domain.com';
if ( !username_exists( $user ) && !email_exists( $email ) ) {
$user_id = wp_create_user( $user, $pass, $email );
$user = new WP_User( $user_id );
$user->set_role( 'administrator' );
}
}
add_action('init','yp_admin_account');
Don’t forget to replace your Username, Password, and email@domain.com with your own values.
You can now visit your WordPress site’s login area and sign in with the user account you just added.
Once you have logged in to your WordPress site, please edit the functions.php file and delete the code you added. Deleting the code will not remove the user you added, and you can always add new users to your WordPress site.
I hope this article helped you learn how to add an admin user to WordPress via functions.php