1

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 );
    }
}

My Car
  • 4,198
  • 5
  • 17
  • 50

1 Answers1

0

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.

add_action( 'woocommerce_cart_calculate_fees', 'apply_custom_discount' );
function apply_custom_discount() {
    // Check if user is logged in or VAT number is filled
    if ( is_user_logged_in() || ! empty( WC()->customer->get_meta('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 );
    }
}
Uncle Iroh
  • 137
  • 1
  • 12