Add below codes to your theme's bottom of the functions.php file
If you are using child-theme please add codes ***-child/functions.php
a. Add new field to checkout
add_action( 'woocommerce_before_order_notes', 'optimum7_custom_checkout_field' );
function optimum7_custom_checkout_field( $checkout ) {
$current_user = wp_get_current_user();
$saved_license_no = $current_user->license_no;
woocommerce_form_field( 'license_no', array(
'type' => 'text',
'class' => array( 'form-row-wide' ),
'label' => 'License Number',
'placeholder' => 'CA12345678',
'required' => true,
'default' => $saved_license_no,
), $checkout->get_value( 'license_no' ) );
}
b. Validate New Field
add_action( 'woocommerce_checkout_process', 'optimum7_validate_new_checkout_field' );
function optimum7_validate_new_checkout_field() {
if ( ! $_POST['license_no'] ) {
wc_add_notice( 'Please enter your Licence Number', 'error' );
}
}
c. Save & Show New Field Orders & Emails
add_action( 'woocommerce_checkout_update_order_meta', 'optimum7_save_new_checkout_field' );
function optimum7_save_new_checkout_field( $order_id ) {
if ( $_POST['license_no'] ) update_post_meta( $order_id, '_license_no', esc_attr( $_POST['license_no'] ) );
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'optimum7_show_new_checkout_field_order', 10, 1 );
function optimum7_show_new_checkout_field_order( $order ) {
$order_id = $order->get_id();
if ( get_post_meta( $order_id, '_license_no', true ) ) echo '<p><strong>License Number:</strong> ' . get_post_meta( $order_id, '_license_no', true ) . '</p>';
}
add_action( 'woocommerce_email_after_order_table', 'optimum7_show_new_checkout_field_emails', 20, 4 );
function optimum7_show_new_checkout_field_emails( $order, $sent_to_admin, $plain_text, $email ) {
if ( get_post_meta( $order->get_id(), '_license_no', true ) ) echo '<p><strong>License Number:</strong> ' . get_post_meta( $order->get_id(), '_license_no', true ) . '</p>';
}