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

如何在WooCommerce中根据所选国家隐藏指定结账字段

WooCommerce约旦配送地址隐藏字段实现方法

你可以通过PHP钩子结合前端JS的方案实现需求,具体操作如下:

1. 加入PHP控制代码

将以下代码添加到你当前使用主题的functions.php文件末尾,或者使用自定义代码片段插件插入:

// 挂载自定义JS到结账页
add_action( 'wp_enqueue_scripts', 'jo_hide_checkout_fields_script' );
function jo_hide_checkout_fields_script() {
    // 仅在结账页加载脚本
    if ( is_checkout() && ! is_wc_endpoint_url() ) {
        // 传递约旦国家码到JS
        wp_localize_script( 'wc-checkout', 'jo_params', array(
            'jo_country_code' => 'JO'
        ) );
        // 插入内联JS逻辑
        wc_enqueue_js( "
            // 监听国家下拉框变化事件
            $('form.checkout').on('change', 'select[name=billing_country], select[name=shipping_country]', function() {
                var selected_country = $(this).val();
                // 判断是否为约旦
                if ( selected_country == jo_params.jo_country_code ) {
                    // 隐藏街道地址、邮政编码字段
                    $('#billing_address_1_field, #billing_postcode_field, #shipping_address_1_field, #shipping_postcode_field').hide();
                    // 清空字段值避免提交
                    $('#billing_address_1, #billing_postcode, #shipping_address_1, #shipping_postcode').val('');
                } else {
                    // 其他国家显示字段
                    $('#billing_address_1_field, #billing_postcode_field, #shipping_address_1_field, #shipping_postcode_field').show();
                }
            });
            // 页面加载完成后初始化执行一次
            $(document).ready(function() {
                $('select[name=billing_country], select[name=shipping_country]').trigger('change');
            });
        " );
    }
}

// 后端校验:如果是约旦,取消字段必填限制,避免提交报错
add_filter( 'woocommerce_billing_fields', 'jo_remove_required_fields', 9999 );
add_filter( 'woocommerce_shipping_fields', 'jo_remove_required_fields', 9999 );
function jo_remove_required_fields( $fields ) {
    // 获取当前用户选择的国家
    $country = WC()->checkout->get_value( 'billing_country' ) ? : WC()->checkout->get_value( 'shipping_country' );
    if ( $country == 'JO' ) {
        $fields['billing_address_1']['required'] = false;
        $fields['billing_postcode']['required'] = false;
        $fields['shipping_address_1']['required'] = false;
        $fields['shipping_postcode']['required'] = false;
    }
    return $fields;
}

2. 效果验证注意事项

  • 代码添加完成后,清空站点缓存再访问结账页测试
  • 如果你的结账页自定义过字段ID,需要对应修改JS里的字段选择器
  • 建议优先将代码添加到子主题的functions.php中,避免主题更新覆盖自定义代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:54:03