基于国家的Woocommerce自定义结账字段

3

我有一个使用WooCommerce的电子商务网站,在结账页面中,如果账单国家设置为“意大利”,则需要激活自定义必填字段“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;
}

但是我不知道如何在国家更改时动态地进行此操作。

2个回答

4
我知道这个问题有点老了,但以下是我解决邮政编码字段最大长度的方法。我的客户使用的是WooCommerce Table Rates运费插件,在美国,如果输入的邮政编码包含完整的9位数字(xxxxx-xxxx),该插件将无法正确计算运费。我们为同一州内的人收取国际运费。
我原本想使用钩子将post_code字段限制为5个字符,但许多国家的邮政编码字符串更长(如加拿大,为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>

-1

我一直在尝试实现类似的功能,但是我想在选择特定的运输方式时显示自定义字段。

以前,我通过将以下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>

1
感谢#Sonic Advisor - 上面的代码修改了运输方式以显示/隐藏类。我在下面发布了一个答案,基于上述代码,根据账单和运输国家修改表单字段。谢谢Sonic Advisor! - Jason

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接