Adding a new WordPress admin user when you don’t have an admin login

      Comments Off on Adding a new WordPress admin user when you don’t have an admin login

If you need to take over the management of a client’s WordPress site but they don’t have or can’t remember the admin login, you are stuck!

However if you have FTP or some other file management access to the server you can put the following PHP file in the website root directory and run it from your browser to create a new admin level user in the database.

Copy and paste the code into a new file named new-admin.php or whatever you prefer.

<?php

// 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.

// CONFIG VARIABLES
// Set these before running the file.

$newusername = 'newadmin';
$newpassword = 'newpassword';
$newemail = 'me@myemailaddress.com';


require_once('wp-blog-header.php');
require_once('wp-includes/registration.php');

// 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.';
}

Before uploading it set the three config values to something suitable. Make sure the password is secure, and choose a username and email address that are unlikely to already exist in that site.

Access the file’s URL in your browser to create the new admin user. Be sure to delete the file as soon as it has been run.

Disclaimer and acknowledgement

This PHP script is offered on an ‘as-is’ basis with no guarantee that it will work correctly etc. Please carry out your own tests before using it. No liability is accepted for any errors or damage however caused. I would appreciate a link to this website if you find it useful.

This PHP script was created from information gleaned from other websites (I do not have a note of the URLs) so is not all my original work and I am not claiming it as such. I will add appropriate acknowledgements if I locate the original sources.