Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wordpress wp_insert_user function

Tags:

php

wordpress

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

like image 326
danyo Avatar asked Sep 04 '12 14:09

danyo


2 Answers

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.

like image 68
Ricardo Rodriguez Avatar answered Oct 03 '22 13:10

Ricardo Rodriguez


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.

like image 38
Ryan S Avatar answered Oct 03 '22 14:10

Ryan S