wp_insert_user

Home » Functions » wp_insert_user

Function Name: wp_insert_user

Explanation: The wp_insert_user function is a powerful WordPress function that allows you to programmatically insert a new user into the WordPress database. It creates a new user account with the specified username, email, password, and user data. This function is commonly used in scenarios where you need to create user accounts dynamically, such as during user registration or when creating user accounts through custom forms.

Usage: To use the wp_insert_user function, you need to provide an array of user data as the parameter. The user data array should include the following key-value pairs:

  1. ‘user_login’: The desired username for the new user.
  2. ‘user_pass’: The desired password for the new user.
  3. ‘user_email’: The email address of the new user.
  4. ‘user_nicename’: (optional) The user-friendly name for the new user.
  5. ‘display_name’: (optional) The display name for the new user.

Here’s an example usage code:

$new_user_data = array(
  'user_login' => 'johnsmith',
  'user_pass' => 'password123',
  'user_email' => 'john@example.com',
  'user_nicename' => 'John Smith',
  'display_name' => 'John'
);

$new_user_id = wp_insert_user( $new_user_data );

if ( ! is_wp_error( $new_user_id ) ) {
  echo 'User created successfully!';
} else {
  echo 'Error creating user: ' . $new_user_id->get_error_message();
}

In this example, we are creating a new user with the username ‘johnsmith’, password ‘password123’, email ‘john@example.com’, user nicename ‘John Smith’, and display name ‘John’. The wp_insert_user function returns the ID of the newly created user, which we store in the $new_user_id variable. We then check if the user was created successfully and display an appropriate message.

Remember to always validate and sanitize the user input before using this function to ensure the security and integrity of your website’s user data.

Learn More on WordPress.org

WordPress snippets using the wp_insert_user function

Register an account to save your snippets or go Pro to get more features.