求助:改造WooCommerce代码实现多配送方式运费求和
WooCommerce 多配送方式运费求和及特定分类商品运费计算解决方案
需求回顾
- 特定分类商品:运费30美元/件,数量每增加1件,运费同步增加30美元(例如2件对应60美元)
- 当前问题:购物车添加其他分类商品后出现多种配送方式,需将所有配送方式的运费求和后计入购物车总计
修改后的代码实现
将以下代码添加到主题的functions.php文件中:
add_filter( 'woocommerce_package_rates', 'calculate_shipping_for_specific_category_and_sum_rates', 10, 2 ); function calculate_shipping_for_specific_category_and_sum_rates( $rates, $package ) { // 1. 定义目标商品分类(替换为你的分类slug或ID) $target_category = 'specific-category'; // 也可使用分类ID,比如 123 $target_category_count = 0; // 2. 统计购物车中目标分类商品的总数量 foreach ( $package['contents'] as $item ) { $product = $item['data']; // 检查商品是否属于目标分类(支持slug或ID匹配) if ( has_term( $target_category, 'product_cat', $product->get_id() ) ) { $target_category_count += $item['quantity']; } } // 3. 计算目标分类商品对应的基础运费(30美元/件) $category_shipping_cost = $target_category_count * 30; // 4. 累加所有现有配送方式的运费 $total_shipping_cost = $category_shipping_cost; foreach ( $rates as $rate ) { $total_shipping_cost += $rate->cost; } // 5. 保留一种配送方式并设置总运费(移除其他方式避免混淆) $remaining_rate_key = array_key_first( $rates ); foreach ( $rates as $rate_key => $rate ) { if ( $rate_key === $remaining_rate_key ) { $rates[$rate_key]->cost = $total_shipping_cost; $rates[$rate_key]->label = '总计运费'; // 可自定义显示名称 } else { unset( $rates[$rate_key] ); } } // 刷新缓存确保运费计算生效 WC()->session->set( 'shipping_method_counts', null ); return $rates; }
代码说明
- 目标分类配置:将
$target_category替换为你需要设置特殊运费的商品分类slug或ID,确保精准匹配目标商品。 - 精准数量统计:仅统计目标分类下的商品总数量,不会受其他分类商品干扰。
- 运费求和逻辑:先计算特定分类商品的基础运费,再叠加现有所有配送方式的运费,得到最终总运费。
- 配送方式简化:只保留一种配送方式并显示总运费,避免顾客面临多种选项的混淆,同时保证购物车总计显示正确金额。
注意事项
- 修改主题
functions.php前请先备份文件,防止代码错误导致网站异常。 - 代码添加后,需清空WooCommerce缓存(路径:WooCommerce > 设置 > 高级 > 页面底部点击"清空缓存"),或切换配送地址触发运费重新计算。
- 若配送方式包含税费等附加费用,可根据需求扩展代码,对
$rate->taxes进行求和处理,确保税费计算准确。
内容的提问来源于stack exchange,提问作者ahmedsyam
相关产品推荐
相关产品推荐

