Creating a Must-Use WordPress Plugin to Add an Admin User If Username Doesn’t Exist

In a single-site WordPress installation, you might encounter scenarios where you need to add an admin user while ensuring that the chosen username doesn’t already exist. We can achieve this by creating a custom “Must-Use” (MU) plugin. This tutorial will guide you through the process of building a “Unique Admin User” MU plugin for your WordPress site.

Step 1: Create a Must-Use Plugin Directory

The first step is to create a directory within your WordPress installation’s “wp-content/mu-plugins” directory. Let’s name this directory “unique-admin-user.”

Step 2: Create the Plugin File

Inside the “unique-admin-user” directory, create a PHP file for your MU plugin, such as “unique-admin-user.php.”

Step 3: Add Plugin Information

Open the “unique-admin-user.php” file and start by adding the necessary information about your plugin. This information includes the plugin name and description.

Plugin Name: Unique Admin User
Description: Add an admin user only if the username does not exist.

Step 4: Check if Username Exists

Next, define a function to check if a username already exists in the WordPress database. This function will be used to determine whether the username you want to add is available.

function is_username_taken($username) {
    $user = get_user_by('login', $username);
    return $user ? true : false;

Step 5: Add the Admin User

Now, create a function that will add a new admin user. You’ll want to customize the username and password as needed in this function.

function add_unique_admin_user() {
    // Replace these values with your desired username and password
    $username = 'new_admin';
    $password = 'your_password';

    if (!is_username_taken($username)) {
        $user_id = wp_create_user($username, $password);
        if (!is_wp_error($user_id)) {
            $user = new WP_User($user_id);
            // You can customize the user role as needed
        } else {
            error_log('Error creating user: ' . $user_id->get_error_message());

Step 6: Hook into an Action

To run your function at the right time, you don’t need to hook into an action since MU plugins are loaded automatically. There’s no need for an action hook in this case.

Step 7: Save and Use

Save the “unique-admin-user.php” file.

Now, your “Unique Admin User” MU plugin is active and will create a new admin user with the specified username and role only if the username is unique. If the username is already taken, the plugin won’t create a duplicate admin user.

Remember to replace ‘new_admin’ and ‘your_password’ with your preferred username and password for the new admin user. You can also customize the user role as needed.

That’s it! You’ve successfully created a Must-Use (MU) plugin to add an admin user only if the chosen username doesn’t exist in your single-site WordPress installation.