Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating programmatically customer's billing information in WooCommerce

I have a form where the user registers to an event, and if they want to they can update some of their billing information on the fly.

I have a list of the informations they can update, for example

 $inputs = array(
        'billing_city'          => 'City',
        'billing_postcode'      => 'Postcode',
        'billing_email'         =>  'Email',
        'billing_phone'         =>  'Phone',
    );

I then tried to use the WC_Customer class to update the changed information:

$customer = new WC_Customer( get_current_user_id() );
foreach ($inputs as $key => $label ) {
     $method = 'set_'. $key;
     $customer->$method( $value );
}

It would seem straight forward enough. However, the billing informations are not changed.

What am I doing wrong? Is there some other function that is supposed to deal with this issue?

Woocommerce documentation doesn't really explain much.

like image 294
DavidTonarini Avatar asked Aug 29 '17 13:08

DavidTonarini


2 Answers

You can do it using update_user_meta() function, this way:

$user_id =  get_current_user_id();

$data = array(
    'billing_city'          => $city_value,
    'billing_postcode'      => $postcode_value,
    'billing_email'         => $email_value,
    'billing_phone'         => $phone_value,
);
foreach ($data as $meta_key => $meta_value ) {
    update_user_meta( $user_id, $meta_key, $meta_value );
}

You will need to set the values in the array.

like image 133
LoicTheAztec Avatar answered Nov 08 '22 15:11

LoicTheAztec


You have to save the changes after setting properties. In your code, after the foreach, add:

$customer->save();

And voila!

like image 38
gmosornoza Avatar answered Nov 08 '22 15:11

gmosornoza