提问者:小点点

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


当特定的产品ID在购物车中时,我试图改变WooCommerce中的税率。我发现在110美元的应答码下,小计设置了“零税”,而且效果很好。我只是不知道如何修改它来检查购物车中的产品ID。


共1个答案

匿名用户

如果年小计低于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', '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;
    $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' );
    }
}