You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;
}

注意事项

  1. 修改代码后,需要进入WooCommerce后台的设置→配送→配送区域,点击每个区域的更新按钮,清除配送方式缓存
  2. 若使用了缓存插件,也需要清除站点缓存

内容的提问来源于stack exchange,提问作者simpleguy94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 16:15:20