Programmatically Create a User in WordPress

July 12, 2012 — 5 Comments

If you're an advanced developer or just want the TL;DR version of this, skip to the code.

When it comes to building a certain type of web app, I obviously think that WordPress is a viable option. Out of all of the contract work I’ve done in the past couple of years, about half of the projects have required some form of user management.

That is, they usually want users to create their own accounts, set a few fields such as their name and email address, and then be emailed when all is setup.

Out of the box, WordPress offers easy user management through its dashboard and if you’re running some type of blog or editorial site, there’s no need to deviate. But if you’re building an application, there are alternative ways to handle users.

Case in point: say that designer has created a solid look and feel for the site. If you force users to use the built-in dashboard to create or manage their profiles, then you’re yanking them out of the site, dropping them into some new experience, and then returning them to the site from which they came.

Lame, right?

There are better ways to introduce user registration and profile management into an app built on WordPress. Though your mileage may vary based on the needs of you project, here’s a how you can programmatically create a user in WordPress.

Before looking at any code, I’m making a number of assumptions throughout the code below. Some may setup registration using Ajax and GET requests; others may use POST requests and do some other type of processing in addition to creating the users.

Whatever the case, all options converge to this:

  • Create a user
  • Set the role
  • Send an email

However you opt to go about getting this data is up to you. To that point, I’ve tried to mark where I’m making assumptions and where the general principles of the API apply.

Required User Data

At the basic level, you really only need two pieces of information to create a user:

  1. An email address
  2. A password

Sure, you can give the user the ability to specify a username if they’d like, but unless the requirements state that a username should be created, I default to an email address every single time. After all, they are unique to each person (and whether we like it or not, they’re kind of our common denominator when it comes to our ID’s on the Internet).

For passwords, you can give users the option to create their own or you can actually let WordPress generate one and then let users change it later. Allowing WordPress to generate it ensures that a secure password will be created and lowers the barrier of registration – doing it this way, they really only have to specify one thing: an email address.

Anyway, so those are two assumptions I’m making:

  1. WordPress will be generating the password
  2. A user’s email address will also serve as their username.

Users, Passwords, Roles, and Emails

Before you get to the point of creating a user, there’s the typical validation and you have to do: make sure the email field isn’t empty, make sure the email address actually looks like an email address, make sure the email address doesn’t already exist in the system, and so on.

All of that is just standard boilerplate user management code. Assuming that the incoming data passes through your validation, you can kick off the user creation process.

Usually, it amounts to four steps:

  1. Generate the password
  2. Create the user
  3. Set the role
  4. Email the user

Throughout the rest of this article, I’m going to be representing the incoming user email address with $email_address.

Does the user exist?

Before doing anything, make sure that the user account doesn’t already exist. This is really easy to do with the username_exists function.

It accepts the username (or, in our case, the email address) as an argument and returns the ID if the account already exists; null otherwise. You can handle that error accordingly.

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

    // More to come...

}

Generate The Password

Assuming that the account doesn’t exist, you want to generate the password. WordPress provides the wp_generate_password function for exactly this.

Though it can accept up to three arguments, I typically tick with the first two – the length of the password to generate and whether or not to include special characters

$password = wp_generate_password( 12, true );

Create The User

Next, I’ll actually create the user profile using wp_create_user which accepts a username, password, and email address, but I’m doubling-up on the email address for the username.

Note also that this function returns the ID of the user (instead of, say, a user object):

$user_id = wp_create_user ( $email_address, $password, $email_address );

Set a Nickname

After that, I like to provide a default nickname for the user. Of course, we really only have the email address but if you’re working with multiple fields or giving users the option to profile their name or some other unique identifier, this is how you’d set their name to display across the site:

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

You can provide a variety of other information into wp_update_user. At the most basic level, you just need to provide the ID of the user you’re updating.

Once the function fires, the user will be updated.

Set The User’s Role

When new users are created in the application, they need some type of default access to the application. Obviously, this is up you or whatever requirements your project calls for, but for demonstration purposes, I’m giving the user the lowest access – a contributor.

To do this, we need to get an instance of the WP_User object. This is done by passing the ID of the new user into the object’s constructor.

$user = new WP_User( $user_id );

After that, set the value of the role using the set_role method:

$user->set_role( 'contributor' );

Email The New User

All that’s left to do is to shoot the user an email that their account has been created. Email Templates can get really complicated really fast and this is not the article for that.

Here, I’m simply emailing the new user and giving them the password that the was generated by WordPress.

wp_mail( $email_address, 'Welcome!', 'Your password is: ' . $password );

I know, weak email, but you get the idea. There are some subtle nuances when working with this function and I recommend reviewing the notes in the codex on this particular function.

Programmatically Creating a User in WordPress

This is the TL;DR version of the code for those of you that skipped down from the introduction of the article, or that got bored reading everything above:


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

  // Generate the password and create the user
  $password = wp_generate_password( 12, false );
  $user_id = wp_create_user( $email_address, $password, $email_address );

  // Set the nickname
  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

Resources in the Codex

Although the code above is sufficient for creating a user, I still recommend reviewing each of the Codex articles to make sure you understand exactly what each function accepts, what it returns, and what you can do with it.

There’s much more flexibility availability with the API – I’ve basically presented the simplest case.

5 responses to Programmatically Create a User in WordPress

  1. Jordan Thornquest March 14, 2013 at 11:56 am

    Hey, Tom! Great article. Concise, to the point, and descriptive! I have a question for you.

    I’m creating a provisioning script that will check and see whether or not a user that is logged into my CAS server has a WordPress account, and if not, will automatically create one with their CAS credentials.

    The creator of the CAS plugin I’m using has a script he provided, but it’s for WordPress MU, which is not only old-school (it’s been replaced with WordPress MultiSite and all), but not what I’m looking for.

    Now, I’m adapting your script to create a single-install version of the aforementioned script, but herein lies my question: within his script, he is setting up the WordPress environment like so:


    // setup the WordPress environment
    define( "WP_INSTALLING", true );
    require( dirname(__FILE__) . '/wp-load.php' );
    require( 'wp-blog-header.php' );
    require_once( ABSPATH . WPINC . '/registration.php' );
    global $domain, $base;

    (I should also mention that the script is run outside of the wpCAS plugin folder in the WordPress root directory; it is called only when CAS can’t find a user in WordPress with credentials matching those within CAS.)

    Is this necessary? Do I need to run similar code?

  2. Tom,

    I have been looking for WEEKS for a SIMPLE explanation of how to create a user registration page. Most of what I found was too clunky, bloated, complex – in some cases other sites expected that I know all about the codex and missed steps.

    You however hit the right medium. Explain the basics and then point to where to get more advanced information.

    Thank you very much for this. Now I can use this information as the foundation, build my registration page and then advance from there as my comfort level grows.

Trackbacks and Pingbacks:

  1. Add Custom User Meta During Registration in WordPress - Tom McFarlin - August 29, 2012

    [...] an example, I thought I’d share how I’m programmatically creating a user during the registration process, adding extra information to the user’s profile, and then [...]

  2. Programmatically Create Categories in WordPress - Tom McFarlin - November 14, 2012

    [...] parts of the website that occur during theme setup. Often times, this includes creating posts, users, and/or setting [...]

Leave a Reply

*

Text formatting is available via select HTML.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>