基于国家/地区的 Woocommerce 自定义结帐字段

Woocommerce custom checkout field based on country

我有一个使用 woocommerce 的电子商务网站 在结帐页面中,如果账单国家/地区设置为 "Italy",我需要激活自定义必填字段 "Codice Fiscale",否则必须删除该额外字段 我的子主题 functions.php 中的代码是

add_filter( 'woocommerce_checkout_fields' , 'field_cfpiva1' );

function field_cfpiva1( $fields ) {
 $fields['billing']['billing_cf'] = array(
  'label'     => __('Codice Fiscale', 'woocommerce'),
  'placeholder'   => _x('Codice Fiscale', 'placeholder', 'woocommerce'),
  'required'  => false,
  'class'     => array('form-row-wide'),
  'clear'     => true
 );

 return $fields;
}

add_filter( 'woocommerce_admin_billing_fields' , 'admin_field_cfpiva1' );

function admin_field_cfpiva1( $fields ) {
 $fields['cf'] = array(
  'label' => __('Codice Fiscale', 'woocommerce'),
  'show'  => true
 );
 return $fields;
}

但我不知道如何在国家/地区更改时动态执行此操作

我一直在尝试实现非常相似的东西,但是在选择特定的运输方式时显示自定义字段。

之前,我通过将以下 jquery 添加到 cart-shipping.php 模板成功地工作,但我似乎无法在 'state' 字段上工作。也许这可能有助于(我们双方)以某种方式达到我们都在寻求的答案......

<script>
    $(document).ready(function (){

        if ($('#shipping_method_0').val() == 'flat_rate:delivered-vic-only'){
            $('#newfield').show();
        }

        $('#shipping_method_0').on('change',function() {
                if ($('#shipping_method_0').val() == 'flat_rate:delivered-vic-only'){
                $('#newfield').show();  
            } else {
            $('#newfield').hide();

            }
        })
    })
    </script>

我知道这个问题有点老了,但这是我更改邮政编码字段最大长度的解决方案。我的客户使用的是 WooCommerce Table 费率运费插件,在美国,如果输入的邮政编码包含完整的 9 位数字 (xxxxx-xxxx),该插件将无法正确计算运费。我们对同一州的人收取国际费率。

我打算使用钩子将 post_code 字段限制为 5,但许多国家/地区的 post 代码字符串更长(例如加拿大,为 6)。感谢#Sonic Advisor。我能够快速修改代码以选择性地更改 post_code 表单字段的 maxlength 属性,如下所示:

<script>
//Limit zip code to 5 digits for United States ONLY
    jQuery(document).ready(function (){

         if (jQuery('#billing_country').val() == 'US'){
            jQuery('#billing_postcode').attr('maxlength','5');

        }

        jQuery('#billing_country').on('change',function() {
                if (jQuery('#billing_country').val() == 'US'){
                jQuery('#billing_postcode').attr('maxlength','5');  
            } else {
            jQuery('#billing_postcode').attr('maxlength','15');

            }
        })

        if (jQuery('#shipping_country').val() == 'US'){
            jQuery('#shipping_postcode').attr('maxlength','5');

        }

        jQuery('#shipping_country').on('change',function() {
                if (jQuery('#shipping_country').val() == 'US'){
                jQuery('#shipping_postcode').attr('maxlength','5');  
            } else {
            jQuery('#shipping_postcode').attr('maxlength','15');

            }
        })
    })
    </script>