questions

Update WooCommerce User programmatically when creating a user

Rate this post

Im trying to create a new user programmatically trough a form but Im having problem with getting the phone numer and country set trough wp_create_user – why wont it take the values? First and last name works as expected.

Relevant code:

$user_id = wp_create_user( $username, $random_password, $user_email ); 
    wp_update_user([
    'ID' => $user_id,
     'first_name' => rgar( $entry, '20.3' ),
     'last_name'  => rgar( $entry, '20.6' ),
     'phone'      => rgar( $entry, '16' ),
     'country'  => rgar( $entry, '24.6' )
    ]);

 

✔️Solution:

In with WooCommerce the phone and the country are billing fields so the right user meta keys are:

  • billing_country (Remember that you need to set a valid country code)
  • billing_phone

You will also need to set the billing_email, billing_first_name and billing_last_name

So your code is going to be instead, replacing also your wp_create_user() function by:

    $username = rgar( $entry, '20.3' );
    $email    = rgar( $entry, '10' );
    $password = wp_generate_password( 12, false );

    $user_data = array(
        'user_login' => $username,
        'user_pass'  => $password,
        'user_email' => $email,
        'role'       => 'customer',
        'first_name' => rgar( $entry, '20.3' ),
        'last_name'  => rgar( $entry, '20.6' ),
    );

    $user_id  = wp_insert_user( $user_data ); // Create user with specific user data

Then to add the WooCommerce user data there is 2 ways:

1). Using WC_Customer Object and methods:

    $customer = new WC_Customer( $user_id ); // Get an instance of the WC_Customer Object from user Id

    $customer->set_billing_first_name( rgar( $entry, '20.3' ) );
    $customer->set_billing_last_name( rgar( $entry, '20.6' ) );
    $customer->set_billing_country( rgar( $entry, '24.6') );
    $customer->set_billing_phone( rgar( $entry, '16' ) );
    $customer->set_billing_email( $email );

    $customer->save(); // Save data to database (add the user meta data)

2) Or using WordPress update_user_meta() function (the old way):

update_user_meta( $user_id, 'billing_first_name', rgar( $entry, '20.3') );
update_user_meta( $user_id, 'billing_last_name', rgar( $entry, '20.6') );
update_user_meta( $user_id, 'billing_country', rgar( $entry, '24.6') );
update_user_meta( $user_id, 'billing_phone', rgar( $entry, '16') );
update_user_meta( $user_id, 'billing_email', $email );

Leave a Reply

Your email address will not be published.

Back to top button