Search code examples
phpwordpresswoocommerceaccountbilling

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.


Solution

  • 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.