How to create an WordPress User/Admin using code

In this tutorial, I will show you how to create a WordPress admin using code. It is useful when the website owner lost the admin email and password.

Adding an Admin User in WordPress Using FTP

The first thing you will need is an FTP client (FileZilla, WinSCP, etc) to connect/access the website files on the server.

Once connected to your WordPress site, you need to find your WordPress theme’s functions.php file.

Path example:

/yourwebsite.com/wp-content/themes/your-current-theme/functions.php

Download your functions.php file in your computer in case you break the entire file code so you could restore it by re-upload old file.

Now open the file the functions.php file and add the following code at the bottom of the file. Make sure to change Username, Password, and Email.

Created an admin user in WordPress using code:

function tia_admin_account(){
$user = 'Username';
$pass = 'Password';
$email = 'example@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','tia_admin_account');

Created an Editor user in WordPress using code:

You can also create a WordPress editor user by just replacing ‘administrator’ with ‘editor’ in set_role() function.


function tia_create_editor_account(){
$user = 'Username';
$pass = 'Password';
$email = 'example@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( 'editor' );
}
}
add_action('init','tia_create_editor_account');

 

Check out how to Create WordPress Custom Post Type And Taxonomy and WP_Query For Custom Post Type With A Custom Taxonomy.

Comments are closed.