根据所选国家/地区设置 WooCommerce 结帐账单字段邮政编码默认值

问题描述 投票:0回答:1

我需要在帐单邮政编码字段中设置默认值,具体取决于所选国家/地区,我使用了以下代码,但它无法正常工作:

add_filter('woocommerce_checkout_fields', 'my_woocommerce_checkout_fields');
add_filter('woocommerce_billing_fields', 'my_woocommerce_billing_fields');

function my_woocommerce_checkout_fields($fields) {
$fields['billing'] = my_woocommerce_billing_fields($fields['billing']);
return $fields;
}

function my_woocommerce_billing_fields($fields) {

global $woocommerce;
$countries = array( 'CO' );

if ( is_checkout() && in_array( $woocommerce->customer->get_billing_country(), $countries ) ){
    
  $fields['billing_postcode']['default'] = '80100';

  $fields['billing_postcode']['custom_attributes']['readonly'] = TRUE;
  $fields['billing_postcode']['custom_attributes']['disabled'] = TRUE;

  return $fields;
 }
}

我必须刷新页面才能看到更改,并且我希望帐单邮政编码字段能够自动更新(如果国家/地区为“CO”),否则该字段应为空。我错过了什么?

jquery woocommerce hook-woocommerce
1个回答
0
投票

使用在本论坛中找到的以下代码并稍作修改即可完成:

add_action( 'wp_footer', 'custom_checkout_script', 10 );
function custom_checkout_script() {
?>
<script type="text/javascript">
    (function($){
        $( 'form.checkout' ).on( 'change', '#billing_country', function() {
            var location = $('#billing_country option:selected').val();
            if( location == 'CO' ) {
                $('input#billing_postcode').val('80100');
            } else if( location != 'CO' && $('input#billing_postcode').val() == '80100' ) {
                $('input#billing_postcode').val('');
            }
        });
    })(jQuery);
    </script>
<?php
}
© www.soinside.com 2019 - 2024. All rights reserved.