基于购物车数量和商品数量的 Woocommerce 条件运输成本降低

Woocommerce conditional shipping cost reduction based on cart amount and item count

我正在寻找一种方法来根据购物车总百分比、统一费率和每种产品的数量来定制降低运费...


6 件产品:固定运费 20 欧元

对于 12 个产品:固定运费 30 欧元

如何做到这一点?

这可以在没有插件的情况下完成……

1) 您首先需要在 WooCommerce 运输设置中为每个运输区域设置 1 的数量 "Flat rate" 方法:

此数量将在我们的函数中更改为 20€ 从 1 到 11 件物品和 30€ 12 件及更多物品。此金额将减去购物车总金额的 10%。


2) 然后使用挂钩在 woocommerce_package_rates 过滤器挂钩中的自定义函数,您将能够根据购物车商品数量和购物车总数对运费进行折扣。

代码如下:

add_filter( 'woocommerce_package_rates', 'custom_package_rates', 10, 2 );
function custom_package_rates( $rates, $packages ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    // Get some cart data and set variable values
    $cart_count = WC()->cart->get_cart_contents_count();
    $cart_total =  WC()->cart->cart_contents_total;
    $cart_10_percent = $cart_total * 0.1;
    $flat_rate_value = 20; // Default "Flat rate" value

    foreach($rates as $rate_key => $rate_values ) {
        $method_id = $rate_values->method_id;
        $rate_id = $rate_values->id;

        if( $method_id == 'flat_rate' ){
            if( $cart_count < 6 )
                $cart_10_percent = 0; // No percent discount
            elseif( $cart_count >= 12 )
                $flat_rate_value = 30; // "Flat rate" value for 12 or more items

            $rate_cost = $flat_rate_value > $cart_10_percent ? $flat_rate_value - $cart_10_percent : 0;

            // Set the new calculated rate cost
            $rates[$rate_id]->cost = number_format( $rates[$rate_id]->cost * $rate_cost, 2 );

            // Taxes rate cost (if enabled)
            $taxes = array();
            foreach ($rates[$rate_id]->taxes as $key => $tax){
                if( $tax > 0 ){ // set the new tax cost
                    // set the discounted tax cost
                    $taxes[$key] = number_format( $tax * $rate_cost, 2 );
                }
            }
            $rates[$rate_id]->taxes = $taxes;
        }
    }
    return $rates;
} 

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

在 WooCommerce 3 上测试并有效。


Refresh the shipping caches (needed sometimes):
1) First empty your cart.
2) This code is already saved on your function.php file.
3) Go in a shipping zone settings and disable one "flat rate" (for example) and "save". Then re-enable that "flat rate" and "save". You are done and you can test it.