Tax Exemption Checkbox With Certificate Number
Adds an "I am tax exempt" checkbox and certificate number to the classic checkout; when ticked, tax is removed and the number is saved on the order.
Opens WPIDE on
Code
add_filter( 'woocommerce_checkout_fields', function ( $fields ) {
$fields['billing']['billing_tax_exempt'] = array(
'type' => 'checkbox',
'label' => 'I am tax exempt',
'class' => array( 'form-row-wide', 'update_totals_on_change' ),
'priority' => 125,
);
$fields['billing']['billing_tax_exempt_id'] = array(
'type' => 'text',
'label' => 'Tax exemption certificate number',
'class' => array( 'form-row-wide' ),
'priority' => 126,
);
return $fields;
} );
add_action( 'woocommerce_checkout_update_order_review', function ( $post_data ) {
parse_str( (string) $post_data, $posted );
WC()->customer->set_is_vat_exempt( ! empty( $posted['billing_tax_exempt'] ) );
} );
add_action( 'woocommerce_after_checkout_validation', function ( $data, $errors ) {
if ( ! empty( $data['billing_tax_exempt'] ) && '' === trim( (string) ( $data['billing_tax_exempt_id'] ?? '' ) ) ) {
$errors->add( 'validation', 'Please enter your tax exemption certificate number.' );
}
}, 10, 2 );
add_action( 'woocommerce_checkout_process', function () {
if ( WC()->customer ) {
WC()->customer->set_is_vat_exempt( ! empty( $_POST['billing_tax_exempt'] ) ); // phpcs:ignore WordPress.Security.NonceVerification
}
} );
Notes
The snippet only checks that a certificate number was entered, so verify numbers before you ship.
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.