Everything WordPress - start till end
Create WordPress admin user through functions.php

Create WordPress admin user through functions.php

We can use php code to create a new wordpress user for us and give it administrator rights. This is especially useful when you’re locked out of your own site and need to create a new user.

Note that this does not work in plugins files, it has to be added to theme functions.php.

How to Create admin user to WordPress through functions.php

Using this method we can create wordpress admin user using ftp or filemanager.

Open wordpress directory and go to wp-content/themes/<your-theme>/functions.php file.

Add this code to the file:

add_action('init', 'add_my_user');
function add_my_user() {
    $username = 'wordpress786_admin_user';
    $email = '[email protected]';
    $password = 'wordpress786_admin_user_pass';

    $user_id = username_exists( $username );
    if ( !$user_id && email_exists($email) == false ) {
        $user_id = wp_create_user( $username, $password, $email );
        if( !is_wp_error($user_id) ) {
            $user = get_user_by( 'id', $user_id );
            $user->set_role( 'administrator' );
        }
    }
}

Now save the file and launch the site once. It’s important to run the site once because the code needs to run once in order for it to create a user.

And you’re done. Now you can login using the WordPress admin username and password that you provided in the code snipped.

Security Advice – How to secure functions.php file

As we see that it is so easy to add an admin user to the site, which means that any hacker who has access to your files can easily create an admin user and thus access everything on your wordpress site.

Therefore it’s recommended to always keep checking the administrators or users of your site. Also keep functions.php file as read only, so that no one can edit it programatically.

Leave a Reply

Your email address will not be published. Required fields are marked *