Here’s the complete code you can add to your theme’s functions.php
file or a custom plugin. This code will add the PAN Number field to the checkout page, save it with the order, display it in the admin panel, and include basic validation:
<?php
// Add PAN Number field to the WooCommerce checkout page
function add_pan_number_checkout_field( $fields ) {
$fields['billing']['billing_pan_number'] = array(
'type' => 'text',
'label' => __('PAN Number', 'woocommerce'),
'placeholder' => __('Enter your PAN number', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true,
);
return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'add_pan_number_checkout_field' );
// Save PAN Number to order meta
function save_pan_number_field( $order_id ) {
if ( isset( $_POST['billing_pan_number'] ) ) {
update_post_meta( $order_id, '_billing_pan_number', sanitize_text_field( $_POST['billing_pan_number'] ) );
}
}
add_action( 'woocommerce_checkout_update_order_meta', 'save_pan_number_field' );
// Display PAN Number in the order admin page
function display_pan_number_in_admin_order( $order ) {
$pan_number = get_post_meta( $order->get_id(), '_billing_pan_number', true );
if ( $pan_number ) {
echo '<p><strong>' . __('PAN Number:', 'woocommerce') . '</strong> ' . $pan_number . '</p>';
}
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_pan_number_in_admin_order', 10, 1 );
// Validate PAN Number format on checkout
function validate_pan_number_field( $fields, $errors ) {
if ( ! empty( $_POST['billing_pan_number'] ) && ! preg_match( '/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/', $_POST['billing_pan_number'] ) ) {
$errors->add( 'validation', __('Please enter a valid PAN Number.', 'woocommerce') );
}
}
add_action( 'woocommerce_checkout_process', 'validate_pan_number_field', 10, 2 );
Steps:
- Copy the code above.
- Go to Appearance > Theme Editor (or use an FTP client if you’re working with files directly).
- Open your theme’s
functions.php
file or create a custom plugin.
- Paste the code at the end of the
functions.php
file or within your plugin file.
- Save the changes.
This code does the following:
- Adds the PAN Number field to the checkout page.
- Saves the entered PAN Number with the order.
- Displays the PAN Number in the WooCommerce admin panel.
- Validates the PAN Number to ensure it follows the correct format.
Let me know if you need further help!