WooCommerce 教程:如何按订单金额设置分级运费

WooCommerce 教程:如何按订单金额设置分级运费

与 Woo 2.6 一起推出的新运输区管理让我们有机会默认添加统一费率,免费送货和本地接送方式。

但是,如果客户根据订单金额(分层运送)需要 3 种不同的费率呢?例如:“订单高达 $ 100,运费= $ 5; 订单高达 $ 250,运费= $ 2; 订单高于 $ 500,运费=免费 “。

这是否可以不使用插件?那么答案,像往常一样是绝对的!

分层运输 – 运输区域设置

转到 WooCommerce> 设置> 运送并创建您的运送区域。在这个例子中,我将针对美国客户,并添加 3 种运输方式:统一费率,统一费率和免费送货。

运输区设置分层运输

2. 分层运输 – 运输方式设置

打开以前添加到该区域的每个运送方法,并重命名/设置它们,如下所示:

  1. 统一费率#1> 重命名为 “低于 $ 100” 的订单,并分配成本= $ 5
  2. 统一费率#2> 重命名为 “低于 $ 250” 的订单,并分配成本= $ 2
  3. 免费送货> 选择 “需要最低订单金额”= $ 500

这是一种方法的设置:

分层运输的运输方式设置

3. 分层运输 – PHP 代码段

现在我们需要 “告诉”WooCommerce,根据订单金额,应该使用固定费率而不是另一个。只有这样,我们才能向最终用户显示正确的运送方式。

First, take a note of the unique ID of the two flat rates. They should look look something like “flat_rate:9“. For more info on how to find it, check here: https://businessbloomer.com/woocommerce-disable-free-shipping-if-cart-has-shipping-class/#woocommerce-how-to-find-shipping-method-id-woo-2-6-after-the-introduction-of-the-new-shipping-zones

Second, let’s code! We’ll need to “unset” flat rate #2 if we are under $100, otherwise we’ll require to “unset” flat rate #1.


/**
* @snippet Tiered Shipping Rates | WooCommerce

* @sourcecode https://businessbloomer.com/?p=21425
* @author Rodolfo Melogli
* @testedwith WooCommerce 2.6.8, WordPress 4.7
*/

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

function bbloomer_woocommerce_tiered_shipping( $rates, $package ) {

  $threshold = 100;

  	if ( WC()->cart->subtotal < $threshold ) {

   		if ( isset( $rates['flat_rate:1'] ) ) unset( $rates['flat_rate:2'] );

	} else {

		if ( isset( $rates['flat_rate:2'] ) ) unset( $rates['flat_rate:1'] );

	}

  return $rates;

}

如何添加此代码?

您可以将 PHP 代码片段放置在主题或子主题的 functions.php 文件的底部(如果是 CSS 代码,请添加到主题的 style.css 文件底部),修改之前建议先备份原始文件,若出现错误请先删除此代码。

此代码是否可用?

或是您有更好的解决方案想要分享?请到薇晓朵 WooCommerce 中文论坛 留言告知,我们希望可以帮到更多国内的 WooCommerce 用户也希望您的参与。

需要关于 WooCommerce 的帮助 ?

文章没看懂?代码不会用?需要帮助您可以去论坛提问自助服务台

作者阿呆

每当你飞起,就是一道彩虹.