Reputation: 2632
I'm trying to add shipping address to the current customer, but I doesn't work.
Here is my code:
$userdata = array(
'user_login' => $email,
'user_email' => $email,
'user_pass' => $password,
'first_name' => $first_name,
'last_name' => $last_name
);
$user = wp_insert_user( $userdata ); // User successfully inserted
$customer = new WC_Customer();
$customer->set_shipping_city("Bangalore"); //Doesn't work
global $woocommerce;
$woocommerce->customer->set_shipping_city("Bangalore"); //Doesn't work
What I am doing wrong?
Upvotes: 1
Views: 1145
Reputation: 253859
I think that the problem is that $user = wp_insert_user( $userdata );
doesn't insert any data, but just store it into $user
variable and after in your code you don't use it anymore.
Then also set_shipping_city();
is a session data function and you need to use an existing customer or cart session (WC_cart).
So I have changed your code a little bit:
$userdata = array (
'user_login' => $email,
'user_email' => $email,
'user_pass' => $password,
'first_name' => $first_name,
'last_name' => $last_name
) ;
$user_id = wp_insert_user( $userdata ) ;
// Here you insert your user data with a 'customer' user role
wp_update_user( array ('ID' => $user_id, 'role' => 'customer') ) ;
//Once customer user is inserted/created, you can retrieve his ID
global $current_user;
$user = wp_get_current_user();
$user_id = $user->ID;
// or use instead: $user_id = get_current_user_id();
// Checking if user Id exist
if( !empty( $user_id ) ) {
// You will need also to add this billing meta data
update_user_meta( $user_id, 'billing_first_name', $first_name );
update_user_meta( $user_id, 'billing_last_name', $last_name );
update_user_meta( $user_id, 'billing_email', $email );
// optionally shipping meta data, that could be different
update_user_meta( $user_id, 'shipping_first_name', $first_name );
update_user_meta( $user_id, 'shipping_last_name', $last_name );
update_user_meta( $user_id, 'shipping_email', $email );
// Now you can insert the required billing and shipping city
update_user_meta( $user_id, 'billing_city', 'Bangalore' );
// optionally shipping_city can be different…
update_user_meta( $user_id, 'shipping_city', 'Bangalore' );
} else {
// echo 'User Id doesn't exist';
}
Then you can use update_user_meta()
function to insert any address data with keys
:
billing_first_name
billing_last_name
billing_company
billing_email
billing_phone
billing_address_1
billing_address_2
billing_country
billing_state
billing_postcode
shipping_first_name
shipping_last_name
shipping_company
shipping_email
shipping_phone
shipping_address_1
shipping_address_2
shipping_country
shipping_state
shipping_postcode
Reference:
Upvotes: 1
Reputation: 1
You can use
wp_update_user( $userdata )
where $userdata are the list of fields.
Using wp_update_user you can update the field
Upvotes: 0