WordPress Admin users can control almost all functionalities of a WordPress website. If you own a WordPress website, you are probably an admin user. You most probably do not have to go through any difficult process to create another admin user. WordPress has a pretty user-friendly interface that allows creating, managing, and deleting users including admins. But in some cases, for some reason, you want to use a code snippet to create a user with admin capabilities on a WordPress installation, you can use the code snippet mentioned here.
Usage
- If you want to dynamically create admin user accounts without having to use the WordPress settings page.
- If you do not have access to the WordPress backend due to some issues but have access to FTP or SSH. You can create an admin user by editing the functions.php file and enter the backend using the newly created information.
- If your WordPress website got hacked and you no longer have access to the backend but can still access the FTP or SSH sections. To regain access, you can create an admin user via the functions.php file.
Code
// Create a WordPress user with Admin capability
function wpt_create_admin_user() {
$username = 'john'; // admin username
$password = '3ddjsTjdsa3'; // admin password
$email = 'example@example.com'; // email address for the account
// Checks if the user already exists
if ( !username_exists( $username ) && !email_exists( $email ) ) {
$userid = wp_create_user( $username, $password, $email );
$user = new WP_User( $userid );
$user->set_role( 'administrator' );
}
}
add_action('init', 'wpt_create_admin_user');
If you want to keep the code cleaner, you may remove the comments (// admin username, // admin password, etc.)
Explanation
- Just a PHP comment, don’t mind it.
- Creating our function
wpt_create_admin_user
to register an admin user.The following 3 are the only values you should change. - Assigning the admin username to the
$username
variable. - Assigning the admin password to the
$password
variable. - Assigning the email to the
$email
variable. - Another comment.
- Checks if the username or email address we previously assigned exists using the
username_exists
andemail_exists
functions by passing our$username
and$email
variables. If it does do not run the code. - Assigning a new variable
$userid
to thewp_create_user()
function and passing our variables as arguments into it. - Then using the
$userid
creating a new instance of the class WP_User which creates a new WordPress user with the provided information. - Setting the role of the newly created user to
administrator
using theset_role
function. - Closing the
if
statement. - Closing the function.
- Adding an action to the
init
by passing ourwpt_create_admin_user
function.