我如何根据Woocommerce中的购物车小计使用不同的运费?
例如:
如果可能的话,我想为500美元的特定产品收费。
答案 0 :(得分:1)
请尝试使用以下功能,根据您的问题中定义的购物车小计,“固定费率”费用将被更改。
如果购物车小计不超过5000,我们将隐藏“固定费率”。您需要启用免费送货方式,“最低订购量”选项为5000 。
使用“统一费率”送货方式,您将需要设置参考送货费用,并且只需简单的初始费用,而不是任何公式。例如可以是1
。这笔费用将根据购物车总重量动态地由我的答案代码代替。
它还会处理特定产品ID ,并且如果在购物车中,则将费用设置为500。
您可能必须在常规运送设置中的“ 运输选项”标签下的“ 启用调试模式”,以禁用临时运送缓存。
代码:
add_filter('woocommerce_package_rates', 'shipping_cost_based_on_price', 12, 2);
function shipping_cost_based_on_price( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
// HERE define the differents costs
$cost1 = 150; // Below 2000
$cost2 = 250; // Below 5000
$cost3 = 500; // Cost for our specific product ID
$step1_subtotal = 2000;
$max_subtotal = 5000;
// HERE DEFINE the specific product ID to be charged at 500
$targeted_product_id = 37;
// The cart subtotal
$subtotal = WC()->cart->get_subtotal();
// Loop through cart items and checking for the specific product
$found = false;
foreach( $package['contents'] as $item ) {
if( $item['product_id'] == $targeted_product_id || $item['variation_id'] == $targeted_product_id ){
$found = true;
break;
}
}
// Loop through the shipping taxes array
foreach ( $rates as $rate_key => $rate ){
$has_taxes = false;
// If subtotal is up to 5000 we enable free shipping only
if( 'free_shipping' !== $rate->method_id && $subtotal >= $max_subtotal ){
unset($rates[$rate_key]);
}
// Targetting "flat rate" only for subtotal below 5000
else if( 'flat_rate' === $rate->method_id && $subtotal < $max_subtotal ){
// Get the initial cost
$initial_cost = $new_cost = $rates[$rate_key]->cost;
// Calculate new cost
if( $subtotal < $step1_subtotal ) { // Below 2000
$new_cost = $cost1;
}
elseif( $subtotal >= $step1_subtotal && $subtotal < $max_subtotal ) { // Between 2000 and below 5000
$new_cost = $cost2;
}
// For the specific product ID (if found in cart items)
if( $found ){
$new_cost = $cost2;
}
// Set the new cost
$rates[$rate_key]->cost = $new_cost;
// Taxes rate cost (if enabled)
$taxes = [];
// Loop through the shipping taxes array (as they can be many)
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $rates[$rate_key]->taxes[$key] > 0 ){
// Get the initial tax cost
$initial_tax_cost = $new_tax_cost = $rates[$rate_key]->taxes[$key];
// Get the tax rate conversion
$tax_rate = $initial_tax_cost / $initial_cost;
// Set the new tax cost
$taxes[$key] = $new_cost * $tax_rate;
$has_taxes = true; // Enabling tax
}
}
if( $has_taxes )
$rates[$rate_key]->taxes = $taxes;
}
}
return $rates;
}
代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。
经过测试,别忘了在出厂设置中禁用“启用调试模式”选项。