Create a New WordPress Admin User from PHP
Posted in Web Development by Josh Winn with 13 Comments
If you’re locked out of WordPress and can’t reset your password, the official docs list several options that allow you to access your administrator account again. But what if you want to create an entirely new admin user? When developing a WordPress site, I typically create an admin user for the development team, set to a general email address, and then another user for the client. That way, the client can manage their own password and reset it when necessary, and we will still will have access for upgrades and changes. For blogs that I have FTP access to, but no working WordPress password, I threw together the following script to create admin users.
How to Use
- Change the configuration variables for username, password, and e-mail
- Save PHP file in your root WordPress directory
- Access the file via your web browser.
- You will see a message with the results. If successful, go ahead and delete the file from your server.
- Log in to WordPress!
Full Source Code
This is tested with WordPress 3.1.2:
// ADD NEW ADMIN USER TO WORDPRESS
// ----------------------------------
// Put this file in your Wordpress root directory and run it from your browser.
// Delete it when you're done.
require_once('wp-blog-header.php');
require_once('wp-includes/registration.php');
// CONFIG
$newusername = 'YOURUSERNAME';
$newpassword = 'YOURPASSWORD';
$newemail = 'YOUREMAIL@TEST.com';
// Make sure you set CONFIG variables
if ( $newpassword != 'YOURPASSWORD' &&
$newemail != 'YOUREMAIL@TEST.com' &&
$newusername !='YOURUSERNAME' )
{
// Check that user doesn't already exist
if ( !username_exists($newusername) && !email_exists($newemail) )
{
// Create user and set role to administrator
$user_id = wp_create_user( $newusername, $newpassword, $newemail);
if ( is_int($user_id) )
{
$wp_user_object = new WP_User($user_id);
$wp_user_object->set_role('administrator');
echo 'Successfully created new admin user. Now delete this file!';
}
else {
echo 'Error with wp_insert_user. No users were created.';
}
}
else {
echo 'This user or email already exists. Nothing was done.';
}
}
else {
echo 'Whoops, looks like you did not set a password, username, or email';
echo 'before running the script. Set these variables and try again.';
}
