I would like to give 10% discount for companies (B2B) but I don’t want to give discount for individual person (B2C). The only way to check if somebody (not logged in) is an individual person or a company is to check the VAT Number field in the checkout page. I need a code which make the following: check permanently the Vat number field is empty or not, if the field is not empty give 10% discount from the subtotal (from the price which not include VAT and shipping cost. I don’t want to give discount from the Vat and shipping cost) if the field is empty do not give discount, the program need to check the field permanently if is empty or not.
I tried this code but it doesn’t work.
add_action( 'woocommerce_cart_calculate_fees', 'apply_custom_discount' );
function apply_custom_discount() {
if( ! empty( $_POST['billing_cod_fiscal'] ) ) {
// Get the subtotal
$subtotal = WC()->cart->subtotal;
// Calculate the discount amount
$discount = $subtotal * 0.1;
// Add the discount to the cart
WC()->cart->add_fee( __( 'Discount', 'text-domain' ), -$discount );
}
}
2
Answers
This code checks if the user is logged in or if the VAT number field is filled. If either of those conditions are true, then the discount is applied. If not, then the discount is not applied.
To give a 10% discount to companies (B2B) based on whether the VAT number field is filled or not, you can use the
woocommerce_cart_calculate_fees
hook to add a custom fee that represents the discount.Here’s an example code snippet that adds a 10% discount to B2B customers’ orders if the VAT Number field is filled:
In the above example, we first check if the user is not logged in using the
is_user_logged_in
function. If the user is not logged in, we then get the value of the "VAT Number" field from the POST request using$_POST['vat_number']
.We then check if the field has any input using
empty
function. If the field has any input, we calculate the discount as 10% of the cart subtotal without taxes and shipping using the formula$subtotal_ex_tax_and_shipping * $discount
.Finally, we add the discount as a fee using the
WC()->cart->add_fee()
method, and only apply the discount if the VAT number field is not empty. The code will check the field permanently in every cart calculation.Note: The
woocommerce_cart_calculate_fees
hook is only triggered when the cart is being calculated, so the discount will only be applied once the customer reaches the cart page. If you want to apply the discount on the checkout page, you may need to use a different hook, such aswoocommerce_review_order_before_shipping
.