Skip to content

Instantly share code, notes, and snippets.

@arfinmilondev
Created March 26, 2025 05:07
Show Gist options
  • Select an option

  • Save arfinmilondev/392b246cdf659bd7f9627c80e5d42b3c to your computer and use it in GitHub Desktop.

Select an option

Save arfinmilondev/392b246cdf659bd7f9627c80e5d42b3c to your computer and use it in GitHub Desktop.
Add New Custom Field in Woo Commerce Checkout Fields
<?php
// Add New Custom Field
add_action( 'woocommerce_before_order_notes', 'wtwh_add_custom_checkout_field' );
function wtwh_add_custom_checkout_field( $checkout ) {
$current_user = wp_get_current_user();
$saved_car_no = $current_user->car_no;
woocommerce_form_field( 'car_no', array(
'type' => 'text',
'class' => array( 'form-row-wide' ),
'label' => 'Car Model Number',
'placeholder' => 'ABC123',
'required' => false,
'default' => $saved_car_no,
), $checkout->get_value( 'car_no' ) );
}
// Validation Field
add_action( 'woocommerce_checkout_process', 'wtwh_validate_new_checkout_field' );
function wtwh_validate_new_checkout_field() {
if ( ! $_POST['car_no'] ) {
wc_add_notice( 'Please enter your Car Model Number', 'error' );
}
}
// Save and Show New Field in WooCommerce Thank You Page, Order Page & Emails
add_action( 'woocommerce_checkout_update_order_meta', 'wtwh_save_new_checkout_field' );
function wtwh_save_new_checkout_field( $order_id ) {
if ( $_POST['car_no'] ) update_post_meta( $order_id, '_car_no', esc_attr( $_POST['car_no'] ) );
}
add_action( 'woocommerce_thankyou', 'wtwh_show_new_checkout_field_thankyou' );
function wtwh_show_new_checkout_field_thankyou( $order_id ) {
if ( get_post_meta( $order_id, '_car_no', true ) ) echo '<p><strong>Car Model Number:</strong> ' . get_post_meta( $order_id, '_car_no', true ) . '</p>';
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'wtwh_show_new_checkout_field_order' );
function wtwh_show_new_checkout_field_order( $order ) {
$order_id = $order->get_id();
if ( get_post_meta( $order_id, '_car_no', true ) ) echo '<p><strong>Car Model Number:</strong> ' . get_post_meta( $order_id, '_car_no', true ) . '</p>';
}
add_action( 'woocommerce_email_after_order_table', 'wtwh_show_new_checkout_field_emails', 20, 4 );
function wtwh_show_new_checkout_field_emails( $order, $sent_to_admin, $plain_text, $email ) {
if ( get_post_meta( $order->get_id(), '_car_no', true ) ) echo '<p><strong>Car Model Number:</strong> ' . get_post_meta( $order->get_id(), '_car_no', true ) . '</p>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment