gpt4 book ai didi

php - 基于购物车商品数量的 WooCommerce 运费

转载 作者:行者123 更新时间:2023-12-05 02:18:17 39 4
gpt4 key购买 nike

我想根据添加到购物车中的产品数量来计算运费,例如,

如果我购买一部手机,则运费为 2.5,如果我购买了两两部以上手机,则运费为 5.0

 <?php

$qty(1) * 2.5 = 2.5

$qty(2) * 2.5 = 5.0

$qty(3) * 2.5 = 5.0

?>

那么有什么想法或建议如何根据产品数量计算运费吗?

最佳答案

Updated:

As your question is a bit unclear, you could just need to add [qty]*2.5 in the Flat rate shipping method cost (for each shipping zone) in your wooCommerce shipping settings.

But it will not work if you have 2 different items in cart like: 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+ 上测试并有效

You will need to refresh shipping zones caches: disabling the Flat rate, then save. And enabling back this rate and save.

关于php - 基于购物车商品数量的 WooCommerce 运费,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45814620/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com