WordPress Code Snippets

A fresh mix of code snippets and tutorials

WordPress Create New User

219

Two ways to programmatically create new users in WordPress. The first method uses wp_create_user() and the second method uses wp_insert_user().

Create new user via wp_create_user()

The easiest way to create a new WordPress user is to use WP’s function wp_create_user(). Here is the basic technique:

$user_login = 'user_login';
$user_pass  = md5($user_pass);
$user_email = 'user_email@example.com';

$user_id = wp_create_user($user_login, $user_pass, $user_email);

The beauty of this technique is its simplicity. The wp_create_user() function accepts only three arguments — name, password, and email — so it’s quick and easy to implement just about anywhere. Upon completion, the function returns either the new user ID or an error. So you can check for successful user creation like so:

if (is_wp_error($user_id)) {
	echo 'Error '. $user_id->get_error_code() .': '. $user_id->get_error_message();
}

Here we are using the following WordPress functions to check and display any errors:

Create new user via wp_insert_user()

If the simplicity of wp_create_user() is not sufficient for your needs, check out the WordPress function, wp_insert_user(). With wp_insert_user(), you can customize more than just the name, email, and password — in fact, you can pass an entire array of parameters or even use the WP_User object. Here is an example showing how it used:

if (email_exists($user_email)) {
	
	echo '<p>Email already registered: '. $user_email .'</p>';
	
} elseif (username_exists($user_login)) {
	
	echo '<p>Username already registered: '. $user_login .'</p>';
	
} else {
	
	$user_pass = wp_generate_password(16, false);
	
	$user_id = wp_insert_user(
		array(
			'user_email' => $user_email,
			'user_login' => $user_login,
			'user_pass'  => $user_pass,
			'user_url'   => $user_url,
			'first_name' => $first_name,
			'last_name'  => $last_name,
			'role'       => $role,
		)
	);
}

Here we are making use of the following WordPress functions:

Notes

If you want to update an existing user, you should use the WordPress function, wp_update_user().

To use either of these functions — wp_create_user() or wp_insert_user() — outside of a plugin or theme, you can include the following WordPress files:

require_once('wp-blog-header.php');
require_once('wp-includes/registration.php');

Adjust the paths if needed to match their actual locations.

Learn more

WordPress Themes In Depth


Show Support

Like our new Facebook Page to show support!