WooCommerce: Add A New Checkout Field

As Per Requirements , sometimes we need to add some extra fields to checkout field and have to save them in order meta for future use.
It’s simply done by 4 steps:

  1. Add html of new field
  2. Validate new field
  3. Save that field value in order meta
  4. Show Data on order page and emails

Step 1 : Add html of new field


function NewCheckoutField( $checkout ) {
  $current_user = wp_get_current_user();
  $saved_license_no = $current_user->license_no;
  woocommerce_form_field( 'gst_no', array(
    'type' => 'text',
    'class' => array( 'form-row-wide' ),
    'label' => 'GST Number',
    'placeholder' => 'GST Number',
    'required' => true,
  ), $checkout->get_value( 'gst_no' ) );
}
add_action( 'woocommerce_before_order_notes', 'NewCheckoutField' );

Step 2 : Validation


function ValidateCheckoutField() {
  if ( ! $_POST['gst_no'] ) {
    wc_add_notice( 'Please enter your GST Number', 'error' );
  }
}
add_action( 'woocommerce_checkout_process', 'ValidateCheckoutField' );

Step 3 : Save Meta Data


function SaveCheckoutFieldMeta( $order_id ) {
  if ( $_POST['gst_no'] ){
    update_post_meta( $order_id, '_gst_no', esc_attr( $_POST['gst_no'] ) );
  }
}
add_action( 'woocommerce_checkout_update_order_meta', 'SaveCheckoutFieldMeta' );

Step 4 : Show Meta Data on Order Page And Emails


function ShowGSTField( $order ) {
  $order_id = $order->get_id();
  if ( get_post_meta( $order_id, '_gst_no', true ) ) {
    echo '<p><strong>GST Number:</strong> ' . get_post_meta( $order_id, '_gst_no', true ) . '</p>';
  }
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'ShowGSTField', 99, 1 );

function SaveCheckoutFieldMetaOnEmail( $order, $sent_to_admin, $plain_text, $email ) {
  if ( get_post_meta( $order->get_id(), '_gst_no', true ) ){
    echo '<p><strong>GST Number:</strong> ' . get_post_meta( $order->get_id(), '_gst_no', true ) . '</p>';
  }
}
add_action( 'woocommerce_email_after_order_table', 'SaveCheckoutFieldMetaOnEmail', 99, 4 );

null
Enjoy

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top