In Woocommerce, I am trying to display Email & Phone input fields as a custom field above billing address section.
This is what I did, but failed:
I created some custom fields and displayed them above the billing section. Also, I set the default Email and Phone fields as optional, and removed them. Woo saves order email as a meta into wp_postmenta
database table. When I save custom fields, I try to overwrite these meta values with $order->update_meta_data()
function, but instead of overwriting it creates a new meta with same meta_key.
function save_extra_checkout_fields( $order, $data ){
if( isset( $data['some_field'] ) ) {
$order->delete_meta_data('_billing_email');
$order->update_meta_data( '_billing_email', sanitize_email( $data['some_field'] ) );
}
}
add_action( 'woocommerce_checkout_create_order', 'save_extra_checkout_fields', 10, 2 );
As you can see even if I try to delete default meta first a duplication occurs.
It is possible to achieve this customization with hooks and filters without hacking the fields in the database, or do you have any idea how to overwrite meta value?
Any help please is welcome.
As billing email is a default field and not custom checkout field, you need to change your code a bit using set_billing_email()
WC_Order
method instead:
add_action( 'woocommerce_checkout_create_order', 'change_billing_email_checkout_field_value', 10, 2 );
function change_billing_email_checkout_field_value( $order, $data ){
if( isset( $data['some_field'] ) && ! empty( $data['some_field'] ) )
$order->set_billing_email( sanitize_email( $data['some_field'] ) );
}
Code goes in function.php file of your active child theme (or active theme). It should works.