Get checkout custom field submitted value using WC_Checkout get_value() method in WooCommerce

Rate this post

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?



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.

Leave a Reply

Your email address will not be published.

Back to top button