I need to set a different tax class for company whose field nip is different than polish in WooCommerce
I have in my checkout field nip, and I want the tax to change to 0% after entering the tax number, e.g. RO123456789. I have 2 class tax Standard and zero rate if I have nip PL123456789 I want the rate to be standard.
i have this code and this didn’t work and I don’t know why.Any guidance on resolving this issue would be highly appreciated.
// Add the Tax Identification Number field at checkout
add_action( 'woocommerce_after_order_notes', 'custom_add_nip_field' );
function custom_add_nip_field( $checkout ) {
echo '<div id="custom_nip_field"><h2>' . __('Dane firmy') . '</h2>';
woocommerce_form_field( 'vat_nip', array(
'type' => 'text',
'class' => array('vat-nip-field form-row-wide'),
'label' => __('Numer NIP (dla firm z UE)'),
'placeholder' => __('Wpisz numer VAT UE'),
), $checkout->get_value( 'vat_nip' ));
echo '</div>';
}
// NIP from field to checkout
add_action( 'woocommerce_checkout_update_order_meta', 'custom_save_nip_field' );
function custom_save_nip_field( $order_id ) {
if ( ! empty( $_POST['vat_nip'] ) ) {
update_post_meta( $order_id, '_vat_nip', sanitize_text_field( $_POST['vat_nip'] ) );
}
}
// Apply 0% VAT for companies from outside Poland based on the NIP number
add_action( 'woocommerce_cart_calculate_fees', 'custom_apply_vat_exemption_based_on_nip' );
function custom_apply_vat_exemption_based_on_nip() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Download the Tax Identification Number from the field at the checkout
$vat_nip = isset( $_POST['vat_nip'] ) ? sanitize_text_field( $_POST['vat_nip'] ) : '';
// Check if the NIP does not start with "PL"
if ( ! empty( $vat_nip ) && substr( $vat_nip, 0, 2 ) !== 'PL' ) {
// Assign a 'zero rate' tax class to the products in your cart
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$cart_item['data']->set_tax_class( 'zero rate' ); // set tax zero rate (0% VAT)
}
}
}
I try some plugins but didn’t work as I expect.
2
Answers
Thanks for code, I would never be able to do it looking at it.
How could I do that?
There are some mistakes and missing things in your current code. JavaScript, Ajax and WooCommerce Sessions are required.
The following code will work with Classic Checkout and is compatible High Performance Order Storage:
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
You could target the billing country code instead of targeting the first 2 characters from the VAT code.