
[英]Set a custom shipping rate cost calculated on cart total weight in WooCommerce
[英]WooCommerce shipping cost calculated by weight of product
我需要组织一个系统来计算 WooCommerce 项目的运费。 这是示例:
如果产品重量小于 19 公斤运费:36$
如果产品重量超过 19 公斤,运费:300$
另外,我需要创建一个额外的运输 class(免费送货)。 这样商店的管理员就可以确定要免费运送的产品。
我如何尝试解决这个问题:
首先在 WooCommerce -> 设置 -> 运输 -> 运输区域中,我创建了新的运输区域(以色列 - 按重量运输),并在该区域中创建了三种不同的运输方式:
然后我在functions.php文件中放了这段代码:
add_filter( 'woocommerce_package_rates', 'custom_tiered_shipping_rates', 9999, 2 );
function custom_tiered_shipping_rates( $rates, $package ) {
if ( WC()->cart->get_cart_contents_weight() < 19 ) {
if ( isset( $rates['flat_rate:21'] ) ) unset( $rates['flat_rate:22'], $rates['flat_rate:24'] );
} elseif ( WC()->cart->get_cart_contents_weight() > 20 ) {
if ( isset( $rates['flat_rate:21'] ) ) unset( $rates['flat_rate:21'], $rates['flat_rate:24'] );
} else {
if ( isset( $rates['flat_rate:21'] ) ) unset( $rates['flat_rate:21'], $rates['flat_rate:22'] );
}
return $rates;
}
我从这里得到的带有详细描述的代码源: WooCommerce:按重量运输(没有插件!)
一切似乎都奏效了。 只有免费送货方式不起作用。 当我给一个产品free_shipping class。 运费不是根据此 class 的可用性计算的,而是根据产品的重量计算的。请帮助修复它。 我知道我在条件中混淆了一些东西。 但是我越是尝试,我现在就越感到困惑。
PS:如果购物车中至少有一件支付运费的商品,那么即使有一件免费送货的商品,运费也应以支付运费为指导。
尝试以下操作,如果只有来自“免费送货”的物品运送 class,它将检查购物车物品。 如果是这种情况并且启用了“免费送货”送货方式,将设置免费送货方式。
在其他情况下,将应用基于重量的统一费率。
请务必在下面的代码中设置正确的运输 class 块,以实现“免费运输”运输 class。
add_filter( 'woocommerce_package_rates', 'custom_tiered_shipping_rates', 9999, 2 );
function custom_tiered_shipping_rates( $rates, $package ) {
// HERE below set the correct shipping class slug for "Free shipping" items.
$free_shipping_class = 'free-shipping';
$free_shipping_only = true;
$non_free_items_weight = 0;
// Check items shipping class for the current shipping package
foreach( $package['contents'] as $cart_item ) {
// For non "Free shipping items" flag them and get the calculated weight.
if( $cart_item['data']->get_shipping_class() !== $free_shipping_class ) {
$free_shipping_only = false;
$non_free_items_weight += $cart_item['data']->get_weight() * $cart_item['quantity'];
}
}
// Free shipping
if ( $free_shipping_only && isset($rates['flat_rate:24']) ) {
unset($rates['flat_rate:21'], $rates['flat_rate:22']);
}
// Other rates (Flat rates)
else {
if ( $non_free_items_weight < 20 && isset($rates['flat_rate:21']) )
unset( $rates['flat_rate:22'], $rates['flat_rate:24'] );
} elseif ( $non_free_items_weight >= 20 && isset($rates['flat_rate:22']) )
unset( $rates['flat_rate:21'], $rates['flat_rate:24'] );
}
}
return $rates;
}
代码进入活动子主题(或活动主题)的functions.php文件。 测试和工作。
不要忘记清空您的购物车以刷新运输缓存。
现在,不要使用“统一费率”进行免费送货,您最好使用 WooCommerce“免费送货”方法(没有限制)并用正确的“免费送货”方法费率 ID 替换代码中的
flat_rate:24
……
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.