phpwordpresswoocommercecart

Set zero tax class to specific item count from defined product categories in Woocommerce


In WooCommerce, if the cart contains 6 or more items from 2 specific categories, then I would like to set a specific tax class (tax-zero) only to these items (not the entire cart, so not change it for the other products).

I use this piece of code which calculates the number of items in cart that are from the 2 categories, but I can't find how to complete it in order to set them with my "tax-zero" tax class.

add_action( 'woocommerce_before_calculate_totals', 'apply_conditionally_taxes', 20, 1 );
function apply_conditionally_taxes( $cart ){

    $item_count   = $cart->get_cart_contents_count();
    $kingcat_count = 0;

    foreach ( $cart->get_cart() as $cart_item ) {
        if ( has_term( 'patisseries', 'product_cat', $cart_item['product_id'] ) or has_term( 'viennoiseries-et-gaufres', 'product_cat', $cart_item['product_id'] ) ) {
            $kingcat_count += $cart_item['quantity'];
            //echo $kingcat_count; 
        }

    }
}

Solution

  • Code contains: (explanation added as a comment to the code)

    function action_woocommerce_before_calculate_totals( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
    
        /* SETTINGS */
    
        // Set categories
        $categories = array ( 'patisseries', 'viennoiseries-et-gaufres' );
    
        // Contains 6 or more items
        $contains_min = 6;
    
        /* END SETTINGS */
    
        // Counter
        $counter = 0;
    
        // Loop trough
        foreach ( $cart->get_cart() as $cart_item ) {
            // Break loop
            if ( $counter >= $contains_min ) {
                break;
            }
    
            // Has term
            if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
                // Add to counter
                $counter += $cart_item['quantity'];
            }
        }
    
        // Check
        if ( $counter >= $contains_min ) {
            // Loop trough
            foreach( $cart->get_cart() as $cart_item ) {
                // Has term
                if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
                    // We set "Zero rate" tax class
                    $cart_item['data']->set_tax_class( 'Zero rate' );
                }
            }
        }
    }   
    add_action( 'woocommerce_before_calculate_totals', 'action_woocommerce_before_calculate_totals', 10, 1 );