danyo
danyo

Reputation: 5846

wordpress wp_insert_user function

I am in the process of creating a custom registration form for WordPress.
My problem is adding custom user meta. I believe the function wp_insert_user will only allow you to add the default fields within the WordPress user table.

Here is my current test code:

$username = '12344';
$password = '1111';
$user_data = array(
'ID' => '',
'user_pass' => $password,
'user_login' => $username,
'display_name' => $loginName,
'first_name' => $firstName,
'last_name' => $lastName,
'role' => get_option('default_role') ,
'user_secondry_email' => '[email protected]'// Use default role or another role, e.g. 'editor'
);
$user_id = wp_insert_user( $user_data );
wp_hash_password( $password );

I have found the add_user_meta function, but this requires an ID to add the metadata. Obviously the user hasn't been created yet so they won't have an ID. Any ideas on how to get around this?

Thanks, Dan

Upvotes: 6

Views: 23209

Answers (4)

Ali Haider
Ali Haider

Reputation: 31

After digging deeper, and checking on my end, I found this script will work just fine. Remove that get_option function and this

$user_data = array(
    'user_login' => $username,
    'user_email' => $email,
    'first_name' => $firstname,
    'last_name' => $lastname,
    'display_name' => $firstname.' '.$lastname,
    'user_pass' => $u_password,
    'role' => 'administrator'
);
$result = wp_insert_user($user_data);

Upvotes: 3

rprasad
rprasad

Reputation: 376

Remove the ID value from the array completely and it should work. (e.g. remove 'ID' => '')

Also, I don't think "user_secondary_email" is an allowed field for the new user array. The field list is here: http://codex.wordpress.org/Function_Reference/wp_insert_user

(In your example, the "user_secondry_email" is missing an 'a')

Good luck!

Upvotes: 1

Ryan S
Ryan S

Reputation: 6474

If I understand your problem correctly you want to add new user_meta to the current registered user.

Here's how I did it.

// this code insert the user, same on your code above just remove the ID field :)
$new_userid = wp_insert_user( $user_data );

$is_success = add_user_meta( $new_userid, 'position', 'programmer', true );
if( $is_success  ) {
   echo 'Successfully added';
} else {
   echo 'Error on user creation';
}

**NOTE:**
$new_userid = Is the return value from adding our new user and use that ID in adding new user meta

Hope this help and other user looking for same solution.

Upvotes: 7

Ricardo Rodriguez
Ricardo Rodriguez

Reputation: 1090

For what I understand from the Wordpress documentation, the ID field is optional.

If it is present, the user is updated, if not, it is created and the ID of the new user is returned by the function.

Upvotes: 7

Related Questions