2

In WooCommerce checkout page, I have added a custom field using the code below:

add_action( 'woocommerce_before_order_notes', 'bbloomer_add_custom_checkout_field' );
function bbloomer_add_custom_checkout_field( $checkout ) { 
    $current_user = wp_get_current_user();
    $saved_gst_no = $current_user->gst_no;

    woocommerce_form_field( 'gst_no', array(        
        'type'        => 'text',        
        'class'       => array( 'form-row-wide' ),        
        'label'       => 'GST Number',        
        'placeholder' => 'GST Number',        
        'required'    => true
        //'default'   => $saved_gst_no,        
    ), $checkout->get_value( 'gst_no' ) );

    error_log( $checkout->get_value( 'gst_no' ) );
}

On entering any value in GST Number field (custom checkout field), then going to payment screen by clicking "Place order" button and returning to checkout page without completing the transaction, all default woocommerce fields like billing phone, email etc are auto filled from the session.

However, the custom field added via above code is always blank. I tried logging the value of $checkout->get_value( 'gst_no' ) and it is always null.

How to make the $checkout object store custom field values?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
dc09
  • 386
  • 2
  • 17

1 Answers1

1

Update 2

Because you need to save 'gst_no' custom field value as user data too. The following will save that custom field as user meta data:

add_action( 'woocommerce_checkout_update_customer', 'action_checkout_update_customer', 10, 2 );
function action_checkout_update_customer( $customer, $data  ) {
    if( isset($_POST['gst_no']) ) {
        $customer->update_meta_data( 'gst_no', sanitize_text_field($_POST['gst_no']) );
    }
}

Code goes in functions.php file of the active child theme (or active theme). It should work.

Note: For info, the WC_Checkout method get_value() use the user meta data.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • The custom field is getting saved as user meta (and order meta as well) successfully. However, it is not getting saved in `$checkout` object, which means that the default value in `woocommerce_form_field` function is always null. This means that if a customer reloads the checkout page, default fields are auto-filled via session even if customer is not logged in but the custom field is always blank and doesn't have the previously entered value. – dc09 Feb 28 '21 at 15:19
  • This works file for a logged in customer, any way to accomplish the same for a guest user? – dc09 Feb 28 '21 at 15:33
  • 1
    Asked a new question for this - https://stackoverflow.com/questions/66411300/how-to-auto-fill-custom-checkout-field-with-previously-entered-value-similar-to – dc09 Feb 28 '21 at 16:30