VAT Number Field on the Block Checkout
Adds an optional VAT number field to the contact section of the Checkout block and rejects numbers that do not look like a VAT number.
Opens WPIDE on
Code
add_action( 'woocommerce_init', function () {
if ( ! function_exists( 'woocommerce_register_additional_checkout_field' ) ) {
return;
}
woocommerce_register_additional_checkout_field( array(
'id' => 'wpide/vat-number',
'label' => 'VAT number (optional)',
'location' => 'contact',
'type' => 'text',
'required' => false,
) );
} );
add_action( 'woocommerce_validate_additional_field', function ( $errors, $field_key, $field_value ) {
if ( 'wpide/vat-number' !== $field_key || '' === trim( (string) $field_value ) ) {
return;
}
$vat = strtoupper( preg_replace( '/[\s.\-]/', '', (string) $field_value ) );
if ( ! preg_match( '/^(AT|BE|BG|CY|CZ|DE|DK|EE|EL|ES|FI|FR|HR|HU|IE|IT|LT|LU|LV|MT|NL|PL|PT|RO|SE|SI|SK|XI|GB|CH|NO)[A-Z0-9+*]{8,12}$/', $vat ) ) {
$errors->add( 'invalid_vat_number', 'Please enter a VAT number with its country prefix, for example DE123456789.' );
}
}, 10, 3 );
Notes
Needs WooCommerce 8.9 or newer; the check covers the format (country prefix plus 8 to 12 characters) and does not contact VIES.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.