我需要指定一个特定字段,在这种情况下是增值税号,这是强制性的,而不是基于用户选择的国家/地区。
就我而言,只有在英国和瑞士,增值税号才必须是可选的。
这是我输入的代码,它在页面加载时立即生效,但当国家/地区发生变化时,它不再执行条件。
它只执行一次交互,就像它只执行一次 if 语句一样。
add_filter('woocommerce_checkout_fields', 'custom_billing_fields', 1000, 1);
function custom_billing_fields( $fields ) {
$user = wp_get_current_user();
global $woocommerce;
$country = $woocommerce->customer->get_country();
//Check user role
//If a company, so professionista role
if ( in_array( 'professionista', (array) $user->roles && $country !== 'GB')) {
//get mandatory VAT field
$fields['billing']['billing_vatcode']['required'] = true;
}
elseif($country == 'GB'){
//remove mandatory VAT field
$fields['billing']['billing_vatcode']['required'] = false;
}
//if is a classic client
else {
//remove other field
unset($fields['billing']['billing_vatcode']);
unset($fields['billing']['billing_pecaddress']);
unset($fields['billing']['billing_recipientcode']);
}
return $fields;
}
我意识到问题可能是因为只有使用 Javascript 才能做到这样的事情,我尝试了:
add_action( 'woocommerce_after_checkout_form', 'bbloomer_shows_notice_shipping' );
function bbloomer_shows_notice_shipping(){
?>
<script>
jQuery(document).ready(function($){
// Set the country code (That will display the message)
var countryCode = 'GB';
$('select#billing_country').change(function(){
selectedCountry = $('select#billing_country').val();
if( selectedCountry == countryCode ){
$("p#billing_vatcode_field").removeClass("validate-required");
$("p#billing_vatcode_field").removeClass("woocommerce-validated");
}
else {
$("p#billing_vatcode_field").addClass("validate-required");
$("p#billing_vatcode_field").addClass("woocommerce-validated");
}
});
});
</script>
<?php
}
但似乎即使阅读,也无法通过在结帐时删除类来删除验证。
我需要帮助。
谢谢!