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

如何通过编程为所有WooCommerce配送方式增加65%费率?

修复WooCommerce配送费率增加65%的函数问题

你的代码存在几个关键问题,导致无法生效:

  • 过滤器参数未接收:woocommerce_package_rates过滤器要求接收$rates和$package两个参数,你的函数没有定义这两个参数,无法获取当前结算的配送费率数据。
  • 逻辑判断错误:!$shipping_method->id === 'free_shipping'的写法存在运算符优先级问题,实际会先对$shipping_method->id取反再做比较,逻辑完全错误,应改为$shipping_method->id !== 'free_shipping'。
  • 操作对象错误:该过滤器的作用是临时修改结算时的配送费率,而非永久修改后台的配送设置,你的代码直接修改并保存配送区域的设置,不符合钩子的设计逻辑。

以下是修复后的代码:

function increase_shipping_costs( $rates, $package ) {
    // 遍历所有可用配送费率
    foreach ( $rates as $rate_key => $rate ) {
        // 排除免费配送方式
        if ( $rate->method_id !== 'free_shipping' ) {
            // 计算增加65%后的费用
            $increased_cost = $rate->cost * 1.65;
            
            // 更新运费金额
            $rates[$rate_key]->cost = $increased_cost;
            
            // 同步增加税费(如果有)
            if ( isset( $rates[$rate_key]->taxes ) && !empty( $rates[$rate_key]->taxes ) ) {
                foreach ( $rates[$rate_key]->taxes as $tax_key => $tax_amount ) {
                    $rates[$rate_key]->taxes[$tax_key] = $tax_amount * 1.65;
                }
            }
        }
    }
    
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'increase_shipping_costs', 10, 2 );

代码说明:

  • 正确接收过滤器的两个核心参数,直接操作当前结算的配送费率数组$rates
  • 仅临时修改本次结算的运费,不会永久改变后台的配送设置
  • 同步处理税费,避免只修改运费导致税费计算偏差

修改代码后,需要在WooCommerce后台「状态 > 工具」中点击「清除配送缓存」,确保新的费率规则生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 05:25:02