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

WooCommerce如何匹配账单州与门店地址动态显隐配送费率

实现方案

1. 提前获取低额固定费率ID

  • 进入WooCommerce后台 → 【设置】→ 【配送】→ 找到你配置了2.5低额费率的对应配送区域
  • 鼠标悬停在该低额固定费率的「编辑」按钮上,浏览器底部状态栏显示的链接里,instance_id=后面的数字就是该费率的唯一ID,先记录下来

2. 插入自定义功能代码

你可以把以下代码加到当前主题的functions.php文件中,或者用自定义代码插件导入:

// 按账单州匹配结果切换低额配送费率显示状态
add_filter( 'woocommerce_package_rates', 'toggle_low_shipping_rate_by_billing_state', 10, 2 );
function toggle_low_shipping_rate_by_billing_state( $rates, $package ) {
    // 配置项1:替换为你实际的低额固定费率ID,格式为flat_rate:你刚才查到的instance_id数字,比如instance_id是4就填flat_rate:4
    $low_shipping_rate_id = 'flat_rate:4';
    // 配置项2:你门店所在区域对应的编码,你自定义的San Antonio对应编码为PA5,无需修改
    $store_state_code = 'PA5';
    // 获取当前客户选择的账单州编码
    $current_customer_state = WC()->customer->get_billing_state();

    // 账单州和门店州不匹配时,移除低额固定费率
    if ( $current_customer_state !== $store_state_code && isset( $rates[$low_shipping_rate_id] ) ) {
        unset( $rates[$low_shipping_rate_id] );
    }
    return $rates;
}

// 自动刷新配送缓存,避免修改后不生效
add_action( 'woocommerce_checkout_update_order_review', 'clear_shipping_cache_on_state_change' );
function clear_shipping_cache_on_state_change() {
    if ( is_cart() || is_checkout() ) {
        WC()->session->set( 'shipping_cache', false );
    }
}

3. 生效测试步骤

  1. 把代码里$low_shipping_rate_id的值替换成你第一步查到的实际费率ID
  2. 进入WooCommerce后台 → 【状态】→ 【工具】→ 点击「清除配送缓存」
  3. 分别选择San Antonio和其他区域测试:选San Antonio时会显示2.5的低额费率,选其他区域时自动隐藏,客户未选择账单州时默认也会隐藏该费率,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:18:03