我想计算自定义运费的基础上购物车金额为woocommerce,我的要求如下,
推车数量
- 0-10 =〉£4.99(运费标识=统一运费:12),
- 10-20 =〉3.99英镑(运费标识=统一运费:13),
- 20-30 =〉£2.99(运费标识=统一运费:14),
- 30-40 =〉£1.99(运费标识=统一运费:15),
- 40岁以上=〉免运费(运费率标识=统一费率:17)
注:我们不计算烟草类别的运费。如果有人购买烟草项目,烟草项目价格不用于运费计算。要完成这一点,所有烟草项目添加到免费送货类(id = 150)。
设置自定义查询以完成上述要求,但它不像我预期的那样工作
add_filter('woocommerce_package_rates', 'custom_shipping_rates_based_on_shipping_class', 11, 2);
function custom_shipping_rates_based_on_shipping_class($rates, $package) {
if (is_admin() && !defined('DOING_AJAX'))
return;
// HERE define your shipping class to find
$class = array(150);
// HERE define the shipping method to change rates for
$shipping_rate_ids = array('flat_rate:12', 'flat_rate:13', 'flat_rate:14', 'flat_rate:15');
// Initialising
$item_price = $item_qty = $item_total = 0;
// Loop through cart items
foreach($package['contents'] as $cart_item_key => $cart_item) {
$item_shipping_class_id = $cart_item['data'] - > get_shipping_class_id();
if (!in_array($item_shipping_class_id, $class)) {
$item_price += $cart_item['data'] - > get_price(); // Sum line item prices that have target shipping class
$item_qty += $cart_item['quantity']; // Sum line item prices that have target shipping class
$item_total = $item_price * $item_qty;
}
}
// Loop through shipping rates
foreach($rates as $rate_key => $rate) {
if (in_array($rate_key, $shipping_rate_ids)) {
if ($item_total > 0 && $item_total < 10) {
$rates[$rate_key] - > cost = 4.99;
unset($rates['flat_rate:13']);
unset($rates['flat_rate:14']);
unset($rates['flat_rate:15']);
unset($rates['flat_rate:17']);
}
elseif($item_total > 10.01 && $item_total < 20) {
$rates[$rate_key] - > cost = 3.99;
unset($rates['flat_rate:12']);
unset($rates['flat_rate:14']);
unset($rates['flat_rate:15']);
unset($rates['flat_rate:17']);
}
elseif($item_total > 20.01 && $item_total < 30) {
$rates[$rate_key] - > cost = 2.99;
unset($rates['flat_rate:12']);
unset($rates['flat_rate:13']);
unset($rates['flat_rate:15']);
unset($rates['flat_rate:17']);
}
elseif($item_total > 30.01 && $item_total < 40) {
$rates[$rate_key] - > cost = 1.99;
unset($rates['flat_rate:12']);
unset($rates['flat_rate:13']);
unset($rates['flat_rate:14']);
unset($rates['flat_rate:17']);
} else {
$rates[$rate_key] - > cost = 0;
unset($rates['flat_rate:12']);
unset($rates['flat_rate:13']);
unset($rates['flat_rate:14']);
unset($rates['flat_rate:15']);
}
}
}
return $rates;
}
上面的代码并不完美的所有场景,请帮助我.
1条答案
按热度按时间olmpazwi1#
如果您知道每种运输方式的shipping_rate_id值,这意味着在WooCommerce插件(WooCommerce〉设置〉运输〉运输区域〉编辑〉运输方式)中,您已经为每种运输方式创建并分配了运费(或免费)。
因此,您无需再次更改每台设备的成本。
此外,对于免费送货的运费将是
free_shipping:17
而不是flat_rate:17
。工作代码为:
该代码已经过测试,可以正常工作。该代码将被放入主题的
functions.php
文件中。