I have added a custom field using the below code:
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' ) );
}
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. How to get the previously entered value auto-filled in the custom field for guest users, similar to the way default woocommerce fields are auto-filled?
2
Answers
Updated (replaced wrong
WC_Session
methodset()
withget()
on the first function)This will work for guest users too. Replace your code with:
Note: Uses a WC_Session variable to store the submitted value for guests, allowing to display it on checkout when returning without completing the transaction.
In my experience, WooCommerce was saving the form data in session variables via AJAX when fields were updated via the
update_order_review
path. In order to hook into this and stored my custom vars, I used the following:Also a deeper way to add the custom checkout fields so that it’s available in the $data passed to
woocommerce_checkout_update_order_meta
: