WooCommerce:启用免运费时无法隐藏其他配送方式问题
问题原因及解决方法
你的代码存在两个核心问题,导致多商品场景下失效:
- 使用
break只收集第一个匹配的免运费方式,若多包裹场景下部分包裹无免运费,或免运费方式排在遍历顺序靠后时,无法正确收集 - 钩子优先级
100可能低于其他修改配送方式的钩子,导致你的代码逻辑被覆盖
修正后的代码
add_filter( 'woocommerce_package_rates', 'cssigniter_hide_other_methods_when_free_shipping_is_available', 200 ); function cssigniter_hide_other_methods_when_free_shipping_is_available( $rates ) { $free_rates = array(); // 遍历所有配送方式,收集所有免运费选项 foreach ( $rates as $rate_id => $rate ) { if ( 'free_shipping' === $rate->method_id ) { $free_rates[ $rate_id ] = $rate; } } // 若存在免运费方式,仅返回免运费;否则返回原方式 return ! empty( $free_rates ) ? $free_rates : $rates; }
额外优化(可选)
如果需要确保仅当订单总额满足免运费条件时才隐藏其他方式,可以添加订单总额检查:
add_filter( 'woocommerce_package_rates', 'cssigniter_hide_other_methods_when_free_shipping_is_available', 200 ); function cssigniter_hide_other_methods_when_free_shipping_is_available( $rates ) { $free_rates = array(); $order_total = WC()->cart->get_subtotal(); $free_shipping_threshold = 50; // 替换为你的免运费阈值 // 仅当订单总额达标时才处理 if ( $order_total >= $free_shipping_threshold ) { foreach ( $rates as $rate_id => $rate ) { if ( 'free_shipping' === $rate->method_id ) { $free_rates[ $rate_id ] = $rate; } } } return ! empty( $free_rates ) ? $free_rates : $rates; }
注意事项
- 修改代码后,需要进入WooCommerce后台的设置→配送→配送区域,点击每个区域的更新按钮,清除配送方式缓存
- 若使用了缓存插件,也需要清除站点缓存
内容的提问来源于stack exchange,提问作者simpleguy94
相关产品推荐
相关产品推荐

