João Paulo Cercal

Staff Security Engineer at LastPass

  • Others

Inserting users in WordPress with wp_insert_user

  • Share on Facebook
  • Share on Twitter
  • Share on LinkedIn

Read this article in

The wp_insert_user function inserts a user into the WordPress database. It can also update a user if the ID key is present in the array passed to the function as a parameter.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php

/**
 * Insere um usuário na base de dados do WordPress
 *
 * @param $userdata mixed Um array com os dados do usuário, stdClass ou um objeto WP_User
 *
 * @return mixed Se sucesso, retorna o ID do usuário que acaba de ser criado,
 *               do contrário retorna um objeto WP_Error
 */
wp_insert_user($userdata);

The $userdata array should contain the following fields:

  • ID an integer, used to update an existing user.
  • user_pass a string, containing a password the user will use.
  • user_login a string, containing a username used during login.
  • user_nicename a string, containing a friendly URL for the username, the default for this field is the username.
  • user_url a string, containing the user’s profile URL.
  • user_email a string, containing the user’s email address.
  • display_name a string, used to display the user’s name within the site. The default value is the username.
  • nickname a string, the user’s nickname, the default value for this field is the username.
  • first_name a string, the user’s first name.
  • last_name a string, the user’s last name.
  • description a string, containing a brief description of the user.
  • rich_editing a string, allowing the text editor to be enabled or disabled.
  • user_registered the date the user was registered, the format used is: Y-m-d H:i:s.
  • role a string, the roles the user will have. By default wordpress provides the following roles: administrator, editor, author, contributor and subscriber.
  • jabber a string, a user’s Jabber account.
  • aim a string, a user’s AOL IM account.
  • yim a string, a user’s Yahoo IM account.Now an example of using this function:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?php

$userdata = array(
  'user_pass'    => '123',
  'user_login'   => 'johndoe',
  'user_url'     => 'https://jpcercal.com',
  'user_email'   => '[email protected]',
  'display_name' => 'John Doe',
  'nickname'     => 'JD',
  'first_name'   => 'John',
  'last_name'    => 'Doe',
  'role'         => 'author',
);

$userId = wp_insert_user($userdata);

In the example above, we saw how easy it is to insert a user into the WordPress database.

So, do you still have any questions? Be sure to comment.