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

WooCommerce按重量计费及满额免运费配置技术求助

问题修复方案

原代码存在的问题

  • 钩子参数错误:woocommerce_package_rates 回调仅接受2个参数,原代码写的10, 16会导致函数无法正常执行
  • 满额免运费逻辑完全缺失:未读取订单总额做判断,反而使用未定义的$value变量做无效校验
  • 重量区间不符合需求:原代码设置的是≤16公斤,与你要求的11-20公斤不符
  • 逻辑顺序不合理:应优先判断满额免运费条件,再处理重量阶梯运费

修正后的代码

add_filter( 'woocommerce_package_rates', 'binary_carpenter_weight_based_shipping_tiers', 10, 2 );
   
function binary_carpenter_weight_based_shipping_tiers( $rates, $package ) {
    // 获取订单商品总额(不含运费、税费,若要含税费可改用 WC()->cart->get_cart_total())
    $order_total = WC()->cart->get_subtotal();

    // 订单总额超过100美元,免运费(保留自提,其他运费方式设为0)
    if ( $order_total >= 100 ) {
        foreach ( $rates as $rate_key => $rate ) {
            if ( $rate->method_id !== 'local_pickup' ) {
                $rates[$rate_key]->cost = 0;
                $rates[$rate_key]->taxes = array(); // 同时免除税费
            }
        }
        return $rates;
    }

    // 获取购物车总重量
    $cart_weight = WC()->cart->cart_contents_weight;

    // 1-10公斤运费规则
    if ( $cart_weight <= 10 ) {
        foreach ( $rates as $rate_key => $rate ) {
            if ( $rate->cost != 4.49 && $rate->method_id !== 'local_pickup' ) {
                unset( $rates[$rate_key] );
            }
        }
    } 
    // 11-20公斤运费规则
    elseif ( $cart_weight <= 20 ) {
        foreach ( $rates as $rate_key => $rate ) {
            if ( $rate->cost != 10 && $rate->method_id !== 'local_pickup' ) {
                unset( $rates[$rate_key] );
            }
        }
    }

    return $rates;    
}

说明

  1. 优先判断订单总额:当商品总价≥100美元时,直接将所有非自提的运费方式费用设为0,同时免除税费
  2. 重量区间修正:调整为1-10公斤、11-20公斤的需求区间
  3. 钩子参数修正:将参数数量改为2,确保函数正常触发
  4. 保留自提方式:所有逻辑中都保留local_pickup选项,不影响用户自提选择

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:25:39