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

如何在WooCommerce中查询最低运费配送方式并修改免费配送标签

WooCommerce 免费配送标签修改方案

核心问题说明

  • wp_options属于全站全局共享数据,不是用户专属数据,你原本的实现方案会导致不同用户访问时配送名称互相覆盖,逻辑完全不可用。
  • 两个钩子执行顺序逻辑错误,同时不需要拆分逻辑存储临时数据,完全可以在单个钩子内完成所有计算。
  • 翻译函数__()使用错误,动态拼接字符串不能传入该函数,仅静态可翻译文本需要使用。

修正后实现代码

add_filter( 'woocommerce_package_rates', 'change_free_shipping_label_with_cheapest', 20, 2 ); 
function change_free_shipping_label_with_cheapest( $rates, $package ) {
    // 初始化变量:最低成本、最低成本配送名称
    $cheapest_cost = PHP_INT_MAX;
    $cheapest_label = '';
    $free_shipping_key = '';

    // 遍历当前包裹的所有配送方式,先找最低成本付费配送和免费配送的key
    foreach( $rates as $rate_key => $rate ) {
        // 跳过成本为0的免费配送,只算付费配送的最低成本
        if( $rate->cost > 0 ) {
            if( $rate->cost < $cheapest_cost ) {
                $cheapest_cost = $rate->cost;
                $cheapest_label = $rate->label;
            }
        }
        // 匹配免费配送的key
        if( $rate->label === __( 'Free Shipping', 'woocommerce' ) ) {
            $free_shipping_key = $rate_key;
        }
    }

    // 如果存在免费配送,且找到了最低成本的付费配送方式,修改标签
    if( $free_shipping_key && !empty($cheapest_label) ) {
        $rates[$free_shipping_key]->label = sprintf( 
            /* translators: %s: Cheapest shipping method name */
            __( 'Free Shipping - %s', 'woocommerce' ), 
            $cheapest_label 
        );
    }

    return $rates;
}

代码说明

  • 所有逻辑在同一个woocommerce_package_rates钩子内完成,不需要额外存储临时数据,每个用户的配送计算完全独立,不会出现数据串用的问题。
  • 增加了兜底逻辑:如果没有找到付费配送方式,不会修改免费配送的原始标签,避免输出异常内容。
  • 修正了翻译函数的用法,符合WordPress开发规范,支持多语言翻译。
  • 不需要额外刷新配送缓存,钩子本身会在配送费率计算时自动触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:06:04