WordPress: insert a user into the database

WordPress stores all user data in two tables, namely wp_users and wp_user_meta. If you've ever tried to insert a new user in the database, you've surely stumbled on some WordPress error while trying to display user preferences or profiles. The point is that both tables work together, so that if you fail to specify some data in one of these tables, you'll get an error. Fortunately, there's a solution.

The solution is the wp_insert_user() function which basically inserts a new user into the database.

Its parameters are contained in an associative array and are as follows:

The $userdata array can contain the following fields
Field Name Description Associated Filter
ID An integer that will be used for updating an existing user. (none)
user_pass A string that contains the plain text password for the user. pre_user_user_pass
user_login A string that contains the users username for logging in. pre_user_user_login
user_nicename A string that contains a nicer looking name for the user. The default is the users username. pre_user_user_nicename
user_url A string containing the users URL for the users web site. pre_user_user_url
user_email A string containing the users email address. pre_user_user_email
display_name A string that will be shown on the site. Defaults to users username. It is likely that you will want to change this, for both appearance and security through obscurity (that is if you dont use and delete the default admin user). pre_user_display_name
nickname The users nickname, defaults to the users username. pre_user_nickname
first_name The users first name. pre_user_first_name
last_name The users last name. pre_user_last_name
description A string containing content about the user. pre_user_description
rich_editing A string for whether to enable the rich editor or not. False if not empty. (none)
user_registered The date the user registered. Format is Y-m-d H:i:s. (none)
role A string used to set the users role. (none)
jabber Users Jabber account. (none)
aim Users AOL IM account. (none)
yim Users Yahoo IM account. (none)

Some caveats:

  1. username, password and e-mail are required
  2. you should always set a role for the newly created user
  3. passwords must be passed as they are, without encrypting or salting them

Example:

 
 wp_insert_user(array(
     'user_login' => 'test',
     'user_pass' => 'test',
     'user_email' => 'test@test.com',
     'role' => 'subscriber'
 ));
 

Leave a Reply

Note: Only a member of this blog may post a comment.