Category

How to Programmatically add a user in WordPress?

When it comes to building a web apps, I obviously consider WordPress as a viable option. Out of all of the web apps that I’ve developed in the past, more than half of them have required some form of user management. That is where you usually want users to create their own accounts, fill out few fields such as their name and email address. This can easily be done with the help of WordPress.

Below is the snippet of code which help you setup a user account once you receive information from the form and then make them automatically sign in. Usually, it amounts to four steps:

1. Setup the form
2. Once form is submitted, get the information
3. Create the user
4. Set the role
5. Email the user (optional)

Note:
1. I am assuming you already know how to setup a form with basic fields of name, email and password. The below code implementation of step 3 to 5.
2. This code needs to be placed in the file where you are receiving the form information.

$email_address = isset($_GET[’email’]) ? $_GET[’email’] : “”;

if( null == username_exists( $email_address ) ) {

$password = $_GET[‘password’]
$user_id = wp_create_user( $email_address, $password, $email_address );

wp_update_user(
array(
‘ID’ => $user_id,
‘nickname’ => $email_address
)
);

// Set the role
$user = new WP_User( $user_id );
$user->set_role( ‘contributor’ );

// Email the user
wp_mail( $email_address, ‘Welcome!’, ‘Your Password: ‘ . $password );

} // end if

Reference: https://codex.wordpress.org/Function_Reference/wp_create_user