Using WordPress ‘add_user()’ PHP function

The add_user() WordPress PHP function creates a new user from the “Users” form using $_POST information.

Usage

To create a new user in WordPress, simply call the add_user() function. This function doesn’t take any parameters, it just uses the $_POST global variable.

add_user();

Parameters

The add_user() function does not take any parameters.

More information

See WordPress Developer Resources: add_user()

Examples

Basic Usage

Call add_user() function after a user submits the form:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Call the function after form submission
    add_user();
}

Check if user is added

This example shows how to check if a user is added successfully or not:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Call the function after form submission
    add_user();

    // Check if user is added
    if (is_user_logged_in()) {
        echo "User added successfully.";
    } else {
        echo "Failed to add user.";
    }
}

Redirect after adding user

Redirect to a certain page after adding a new user:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Call the function after form submission
    add_user();

    // Redirect to the homepage after adding user
    wp_redirect(home_url());
    exit();
}

Prevent spam registration

Limit the number of registrations from a single IP address to prevent spam:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the IP address
    $ip_address = $_SERVER['REMOTE_ADDR'];

    // Get the number of users registered from this IP
    $user_count = count_users_from_ip($ip_address);

    // Limit the number of registrations
    if ($user_count < 5) {
        // Call the function after form submission
        add_user();
    } else {
        echo "You have reached the limit of registrations from this IP address.";
    }
}

Add user with specific role

Add a user with a specific role:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Call the function after form submission
    add_user();

    // Get the ID of the last registered user
    $user_id = get_last_registered_user_id();

    // Set the role of the user
    $user = new WP_User($user_id);
    $user->set_role('contributor');
}