New field on checkout is shown but it’s not saved on the order details

I am having a problem adding a custom field on the checkout of WooCommerce, I am using this code:

add_filter('woocommerce_checkout_fields','custom_override_checkout_fields');
function custom_override_checkout_fields($fields) {
    $fields['billing']['billing_colonia'] = array(
        'label' => __('Colonia', 'woocommerce'),
        'placeholder' => _x('', 'placeholder', 'woocommerce'),
        'required' => true,
        'class' => array('form-row-wide'), 
        'clear' => true
    );
    
    $fields['shipping']['shipping_colonia'] = array(
        'label' => __('Colonia', 'woocommerce'),
        'placeholder' => _x('', 'placeholder', 'woocommerce'),
        'required' => true,
        'class' => array('form-row-wide'), 
        'clear' => true
    );
    return $fields;
}

It indeed shows the field on the checkout form, but I fill it and I complete an order and nothing about this new field is saved on any order at /wp-admin/edit.php?post_type=shop_order

Should I do something to save that info? What is the correct way to add a custom field there?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

As far as I remember you need to manually save your custom fields values via woocommerce_checkout_update_order_meta hook. Try

add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_fields_update_order_meta' );
function custom_checkout_fields_update_order_meta( $order_id ) {
    update_post_meta( $order_id, 'billing_colonia', sanitize_text_field( $_POST['billing_colonia'] ) );
    update_post_meta( $order_id, 'shipping_colonia', sanitize_text_field( $_POST['shipping_colonia'] ) );
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x