Yahya Essam Yahya Essam - 3 months ago 35
PHP Question

Avoid WooCommerce Checkout Billing form to overwrite default Wordpress user data

in the database we have metauser table that contain:

The

first_name
and
last_name
fields


Those are the default Wordpress first and last name.

And also we have:

The
billing_first_name
and
billing_last_name
.

now when user fill out the billing form and proceed the checkout process,
Woocommerce update both fields with the new values from billing name fields
(the default ones).

I have tried many things used actions like:

woocommerce_before_checkout_billing_form


or

woocommerce_after_checkout_billing_form


Also tried to update meta with:

update_user_meta()


But it's not working.

I want it to not overwrite the default first_name and last_name,
but keep the new values only in billing_first_name and billing_last_name


I think the default process is like that

https://gist.github.com/claudiosanches/ae9a8b496c431bec661b69ef73f1a087

Any help on this please?

Answer Source

The way is to use a custom funtion hooked in woocommerce_checkout_update_customer action hook:

add_action('woocommerce_checkout_update_customer','custom_checkout_update_customer', 10, 2 );
function custom_checkout_update_customer( $customer, $data ){

    if ( ! is_user_logged_in() || is_admin() ) return;

    // Get the user ID
    $user_id = $customer->get_id();

    // Get the default wordpress first name and last name (if they exist)
    $user_first_name = get_user_meta( $user_id, 'first_name', true );
    $user_last_name = get_user_meta( $user_id, 'last_name', true );

    if( empty( $user_first_name ) || empty( $user_last_name ) ) return;

    // We set the values by defaul worpress ones, before it's saved to DB
    $customer->set_first_name( $user_first_name );
    $customer->set_last_name( $user_last_name );
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works in WooCommerce 3+