This code snippet allows you to create an administrator then delete it after you’re done with your work on the website. It’s very useful when the client gives you only FTP or CPanel and you have many websites to work on.
How to Use
Simply:
- Add the code to your active theme
functions.php
file. - Change the values on the
$userdata
table. Make sure you use a strong password. Some websites, especially those with Wordfence security installed will refuse to create accounts with weak passwords. - Create the administrator by accessing this URL (use your domain name):
https://example.com/?create_admin=1
- Do your work on the website.
- Delete the administrator by accessing this URL (use your domain name):
https://example.com/?delete_admin=1
The Code
/**
* Change these.
*/
$userdata = [
'user_email' => 'admin@example.com',
'user_pass' => '**Example Password**',
'user_login' => 'example-admin',
];
/**
* Create the administrator.
*
* You can create the administrator by visiting any page of the website
* with create_admin=1 added to the URL (https://example.com/?create_admin=1).
*/
if ( ! empty( $_GET[ 'create_admin' ] ) ) {
add_action('init', function() use ( $userdata ) {
if ( ! username_exists( $user ) && ! email_exists( $email ) ) {
$userdata[ 'role' ] = 'administrator';
wp_insert_user( $userdata );
}
} );
}
/**
* Delete the administrator.
*
* You can delete the administrator by visiting any page of the website
* with delete_admin=1 added to the URL (https://example.com/?delete_admin=1).
*/
if ( ! empty( $_GET[ 'delete_admin' ] ) ) {
add_action('init', function() use ( $userdata ) {
$user = get_user_by( 'email', $userdata[ 'user_email' ] );
if ( $user ) {
require_once( ABSPATH . 'wp-admin/includes/user.php' );
wp_delete_user( $user->ID );
}
} );
}