根据 WooCommerce 中的购物车小计,将特定应税运费成本设置为 0

Set specific taxable shipping rate cost to 0 based on cart subtotal in WooCommerce

使用以下代码,当购物车小计达到特定值时,我可以使用特定运费方法 (此处 'easypack_parcel_machines') 将成本设置为 0金额 (此处为 150 波兰兹罗提):

function override_inpost_cost( $rates, $package ) {
    // Make sure paczkomaty is available
    if ( isset( $rates['easypack_parcel_machines'] ) ) {
        // Current value of the shopping cart
        $cart_subtotal = WC()->cart->subtotal;
        // Check if the subtotal is greater than 150pln
        if ( $cart_subtotal >= 150 )    {
            // Set the cost to 0pln
            $rates['easypack_parcel_machines']->cost = 0;

        }
    }
    
    return $rates;
}

add_filter( 'woocommerce_package_rates', 'override_inpost_cost', 10, 2 );

但问题是运费税原始成本仍然存在,即使 'easypack_parcel_machines' 运输方式费率成本设置为其原始成本为零(因为它是应税的)。

如何更改代码,以便如果 'easypack_parcel_machines' 送货方式费率成本设置为 0,税费也将设置为零?

注意:由于一些插件或一些自定义代码可以将购物车分成多个运输包裹,正确的方法是获取当前包含的相关购物车商品的小计运输包裹。

您的代码中缺少的是将税收设置为零,如下所示:

add_filter( 'woocommerce_package_rates', 'override_inpost_shipping_method_cost', 10, 2 );
function override_inpost_shipping_method_cost( $rates, $package ) {
    $targeted_shipping_rate_id = 'easypack_parcel_machines'; // <== Define shipping method rate Id
    
    // Make sure that our shipping rate is available
    if ( isset( $rates[$targeted_shipping_rate_id] ) ) {
        $cart_subtotal_incl_tax = 0; // Initializing

        // Get cart items subtotal for the current shipping package
        foreach( $package['contents'] as $cart_item ) {
            $cart_subtotal_incl_tax += $cart_item['line_subtotal'] + $cart_item['line_subtotal_tax'];
        }
        
        // Check if the subtotal is greater than 150pln
        if ( $cart_subtotal_incl_tax >= 150 )    {
            // Set the cost to 0pln
            $rates[$targeted_shipping_rate_id]->cost = 0;

            $taxes = array(); // Initializing

            // Loop through the shipping method rate taxes array
            foreach( $rates[$targeted_shipping_rate_id]->taxes as $key => $tax_cost ) {
                $taxes[$key] = 0; // Set each tax to Zero
            }

            if ( ! empty($taxes) ) {
                $rates[$targeted_shipping_rate_id]->taxes = $taxes; // Set back "zero" taxes array
            }
        }
    }

    return $rates;
}

代码进入活动子主题(或活动主题)的 functions.php 文件。它应该有效。

注意:不要忘记清空购物车以刷新运输缓存数据。