![](/img/trans.png)
[英]Woocommerce conditional shipping cost reduction based on cart amount and item count
[英]WooCommerce shipping cost based on cart item count
我想根据添加到购物车的产品数量来计算运费,例如,
如果我购买一部手机,那么它会将运费计为 2.5,如果我购买了两部或两部以上的手机,则运费将为 5.0
<?php
$qty(1) * 2.5 = 2.5
$qty(2) * 2.5 = 5.0
$qty(3) * 2.5 = 5.0
?>
那么有什么想法或建议如何根据产品数量计算运费吗?
更新:
由于您的问题有点不清楚,您可能只需要在 wooCommerce 运输设置中的统一费率运输方式成本(针对每个运输区域)中添加
[qty]*2.5
。但是,如果您的购物车中有 2 件不同的商品,例如:
item1 (qty 1) + item2 (qty 1)
所以这个答案将适用于所有情况:
1) 首先,您需要为每个运输区域设置“统一费率”运输方式,其成本将设置为2.5
(在您的 WooCommerce 运输设置中)。
2)添加此代码,它将为每个购物车项目(基于项目的总数量)计算新的更新运费:
add_filter( 'woocommerce_package_rates', 'custom_flat_rate_cost_calculation', 10, 2 );
function custom_flat_rate_cost_calculation( $rates, $package )
{
// The cart count (total items in cart)
$cart_count = WC()->cart->get_cart_contents_count();
$taxes = array();
// If there is more than 1 cart item
if( $cart_count > 1 ){
// Iterating through each shipping rate
foreach($rates as $rate_key => $rate_values){
// Targeting "Flat Rate" shipping method
if ( 'flat_rate' === $rate_values->method_id ) {
// Set the new calculated rate cost
$rates[$rate_id]->cost = number_format($rates[$rate_id]->cost * $cumulated_active_quantity, 2);
// Taxes rate cost (if enabled)
foreach ($rates[$rate_id]->taxes as $key => $tax){
if( $rates[$rate_id]->taxes[$key] > 0 ){ // set the new tax cost
$taxes[$key] = number_format( $rates[$rate_id]->taxes[$key] * $cumulated_active_quantity, 2 );
$has_taxes = true;
} else {
$has_taxes = false;
}
}
if( $has_taxes )
$rates[$rate_id]->taxes = $taxes;
}
}
}
return $rates;
}
代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中。
此代码已在 WooCommerce 3+ 上进行测试并有效
您将需要刷新运输区域缓存:禁用统一费率,然后保存。 并启用此速率并保存。
您可以添加自定义费用:添加到主题functions.php 或使用插件
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$price_per_mobile = 2.5;
$shipcharge = ( $woocommerce->cart->cart_contents_total * $price_per_mobile);
$woocommerce->cart->add_fee( 'Total Shipping Cost', $shipcharge, true, '' );
}
继续使用 Woocommerce 过滤器woocommerce_package_rates
。 您可以在其中自定义购物车页面中可用的所有运费。
这是为国内和国际运输的所有物品添加额外费用的代码
add_filter('woocommerce_package_rates', 'wf_modify_rate', 10, 3);
function wf_modify_rate( $available_shipping_methods, $package ){
$origin_country = 'US';
$amount_to_add_domestic = 10;
$amount_to_add_inter_national = 20;
$amount_to_add = ($package['destination']['country'] == $origin_country) ?
$amount_to_add_domestic : $amount_to_add_inter_national;
$item_count = 0;
foreach ($package['contents'] as $key => $item) {
$item_count += $item['quantity'];
}
foreach ($available_shipping_methods as $methord_name => $methord) {
$available_shipping_methods[$methord_name]->cost += ($amount_to_add*$item_count);
}
return $available_shipping_methods;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.