Using WordPress ‘create_user()’ PHP function

The create_user() WordPress PHP function is an alias of wp_create_user(). It’s used to create a new user in the WordPress system.

Usage

Here’s a simple example of how to use create_user():

$new_user_id = create_user('johndoe', 'password123', '[email protected]');

In the above example, a new user with the username ‘johndoe’, password ‘password123’, and email ‘[email protected]’ is created. The function returns the ID of the new user.

Parameters

  • $username (string) – Required. The username of the new user.
  • $password (string) – Required. The password for the new user.
  • $email (string) – Required. The email address of the new user.

More information

See WordPress Developer Resources: create_user()

This function is an alias of wp_create_user(), and it’s available since WordPress version 2.0.0.

Examples

Basic usage

// Create a new user
$new_user_id = create_user('johndoe', 'password123', '[email protected]');

// The new user ID is now stored in $new_user_id

This example creates a new user with the username ‘johndoe’, password ‘password123’, and email ‘[email protected]’. The new user’s ID is stored in the $new_user_id variable.

User creation with error checking

$new_user_id = create_user('johndoe', 'password123', '[email protected]'); 
// Check for errors 
if (is_wp_error($new_user_id)) { 
echo $new_user_id->get_error_message(); 
}

This example also creates a new user, but it includes error checking. If user creation fails, an error message is displayed.

Assigning a role to the new user

$new_user_id = create_user('johndoe', 'password123', '[email protected]'); 
// Assign a role to the new user 
$user = new WP_User($new_user_id); 
$user->set_role('editor');

This example creates a new user and assigns the ‘editor’ role to them.

Adding additional information to the user profile

$new_user_id = create_user('johndoe', 'password123', '[email protected]');

// Add additional information to the user profile update_user_meta($new_user_id, 'first_name', 'John'); update_user_meta($new_user_id, 'last_name', 'Doe');

This example creates a new user and adds additional information (first and last name) to their user profile.

Sending a notification email to the new user

$new_user_id = create_user('johndoe', 'password123', '[email protected]');

// Send a notification email to the new user wp_new_user_notification($new_user_id, null, 'user');

This example creates a new user and sends a notification email to the new user.