Sometimes, you might need to create an administrator account in WordPress without being able to access the admin dashboard. This could be because you have lost access to your site’s admin panel or when troubleshooting a client’s website. In this tutorial, we will show you how to programmatically add a WordPress administrator account using the functions.php file and FTP.
Steps to Add an Admin Account
1. Access Your Site via FTP
First, connect to your WordPress site using an FTP client like FileZilla or through your hosting’s file manager. Once connected:
1. Navigate to the /wp-content/themes/ directory.
2. Open the folder of your active theme.
3. Locate the functions.php file.
2. Insert the Code
Add the following code snippet to your functions.php file:
function mukto_admin_account(){
$user = 'Username';
$pass = 'Password';
$email = 'name@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','mukto_admin_account');
3. Save and Upload the File
Save the file and upload it back to your server via FTP.
How the Code Works
1. Define User Information:
The code sets a username, password, and email for the new administrator account.
2. Check for Existing Users:
Before creating the account, the username_exists()
and email_exists()
functions check if the username or email is already in use.
3. Create the Account:
If the checks pass, wp_create_user()
creates the account, and the WP_User
class assigns the administrator role.
4. Hook It to init:
The add_action('init', 'wpb_admin_account')
ensures the function runs when WordPress initializes.
Test the Admin Account
- Visit your WordPress login page (/wp-admin).
- Use the new credentials to log in.
- Verify that the account has administrator privileges.
Remove the Code After Use
Leaving the code in your functions.php file is a security risk, as anyone accessing your site could potentially trigger it. Once the account is created:
- Reopen the functions.php file.
- Delete the code snippet.
- Save and re-upload the file to your server.
This method is a lifesaver when access to the WordPress dashboard is restricted. Just ensure you follow the steps carefully to maintain the security and integrity of your site.