WordPress

How to add a new admin user to WordPress using functions.php

  1. Add the following code to your themes functions.php file.
// Add a new admin user to WordPress on initialization
add_action('init', 'ec_add_new_wp_user');

function ec_add_new_wp_user() {

    // For enhanced security, use a difficult-to-predict username
    $username = 'blaEuzvTvW';

    // Generate a random password
    $password = wp_generate_password();

    // Set other user credentials
    $email_address = 'your@email.com';

    // Check if the username already exists
    if (!username_exists($username)) {
        // Create a new user
        $user_id = wp_create_user($username, $password, $email_address);

        // Get the user object
        $user = get_user_by('ID', $user_id);

        // Assign the 'administrator' role to the user
        if ($user instanceof WP_User) {
            $user->set_role('administrator');
        }
    }
}

  1. Visit your website.
  2. Log in to WordPress Dashboard.
  3. Remove the code from functions.php

See Function Reference wp create user – WordPress Codex

Was this guide helpful?

Need help with this?

Open a ticket and link to this guide so our team can see what you have tried.

View support tickets

Power your business with Ecenica Hosting

Built for WordPress and serious websites. Fast, secure and supported by real people in the UK.

Ecenica hosting services represented by a connected red route across London