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

如何在WooCommerce中仅限制配送州/省,不限制账单州/省?

仅限制WooCommerce配送字段的西班牙省为瓦伦西亚

要实现仅对配送地址的西班牙省/州做限制、不对账单地址生效的需求,你需要替换原来的全局woocommerce_states钩子,改用woocommerce_form_field_args钩子针对性修改配送字段的选项:

add_filter( 'woocommerce_form_field_args', 'tl45r_restrict_shipping_state_to_valencia', 10, 3 );
function tl45r_restrict_shipping_state_to_valencia( $args, $key, $value ) {
    // 仅针对配送州字段生效
    if ( 'shipping_state' === $key ) {
        // 获取当前选中的配送国家(优先取表单提交数据,其次取用户会话数据)
        $country = isset( $_POST['shipping_country'] ) ? wc_clean( $_POST['shipping_country'] ) : WC()->customer->get_shipping_country();
        
        // 当国家为西班牙时,替换州选项为仅瓦伦西亚
        if ( 'ES' === $country ) {
            $args['options'] = array(
                '' => __( 'Select a province…', 'woocommerce' ),
                'V' => __( 'Valencia', 'woocommerce' )
            );
        }
    }
    
    return $args;
}

代码说明:

  • 利用woocommerce_form_field_args钩子精准定位到配送州字段shipping_state,避免影响全局或账单字段
  • 通过判断当前选中的配送国家动态调整选项,只有当用户选择西班牙时,配送州下拉框才会只显示瓦伦西亚
  • 保留了WooCommerce默认的空选项提示,符合原生表单交互逻辑
  • 账单地址的州字段依然保留所有西班牙省/州的默认选项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 21:33:13