WooCommerce:当特定产品在购物车中时更改税率

问题描述

当购物车中有特定产品 ID 时,我正在尝试更改 WooCommerce 中的税率。我找到了 Set 'Zero Tax' for subtotal under $110 - Woocommerce 答案代码并且它有效。我只是不知道如何修改它以检查购物车中的产品 ID。

解决方法

如果小计低于 110 美元,以下将为特定产品设置“零税”:

add_action( 'woocommerce_before_calculate_totals','apply_conditionally_zero_tax_rate',10,1 );
function apply_conditionally_zero_tax_rate( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    $targeted_product_ids = array(37,53); // Here define your specific products
    $defined_amount = 110;
    $subtotal = 0;

    // Loop through cart items (1st loop - get cart subtotal)
    foreach ( $cart->get_cart() as $cart_item ) {
        $subtotal += $cart_item['line_total'];
    }

    // Targeting cart subtotal up to the "defined amount"
    if ( $subtotal > $defined_amount )
        return;

    // Loop through cart items (2nd loop - Change tax rate)
    foreach ( $cart->get_cart() as $cart_item ) {
        if( in_array( $cart_item['product_id'],$targeted_product_ids ) ) {
            $cart_item['data']->set_tax_class( 'zero-rate' );
        }
    }
}

或者当任何特定产品在购物车中并且小计低于 110 美元时,以下将设置“零税”:

add_action( 'woocommerce_before_calculate_totals',53); // Here define your specific products
    $defined_amount = 110;
    $subtotal = 0;
    $found = false;

    // Loop through cart items (1st loop - get cart subtotal)
    foreach ( $cart->get_cart() as $cart_item ) {
        $subtotal += $cart_item['line_total'];

        if( in_array( $cart_item['product_id'],$targeted_product_ids ) ) {
            $found = true;
        }
    }

    // Targeting cart subtotal up to the "defined amount"
    if ( ! ( $subtotal <= $defined_amount && $found ) )
        return;

    // Loop through cart items (2nd loop - Change tax rate)
    foreach ( $cart->get_cart() as $cart_item ) {
        $cart_item['data']->set_tax_class( 'zero-rate' );
    }
}