【发布时间】:2020-08-28 04:44:27
【问题描述】:
在我的 Wordpress Woocommerce 网站中,当用户选择特定的计费国家/地区时,我需要跳过所需的计费城市字段验证。
我在以下类似问题中提供了答案,但这两个问题似乎都不适用于我的结帐页面。我所做的只是将这些函数复制粘贴到活动主题的 functions.php 中,并相应地更改字段和函数名称。但是结帐页面的源代码中没有出现更改或代码,并且所需的验证仍然适用于不需要输入城市的国家/地区。
推荐(以下答案均不适用于我的结帐页面)
Make checkout phone field optional for specific countries in WooCommerce
Make Woocommerce checkout phone field optional based on shipping country
我的代码
// Making the billing city field not required (by default)
add_filter( 'woocommerce_billing_fields', 'filter_billing_city_field');
function filter_billing_city_field( $fields ) {
$fields['billing_city']['required'] = false;
return $fields;
}
// Real time country selection actions
add_action( 'woocommerce_after_order_notes', 'custom_checkout_scripts_and_fields', 8, 1 );
function custom_checkout_scripts_and_fields( $checkout ) {
$required = esc_attr__( 'required', 'woocommerce' );
// HERE set the countries codes (2 capital letters) in this array:
$countries = array( 'LK');
// Hidden field for the phone number validation
echo '<input type="hidden" name="billing_city_check" id="billing_city_check" value="0">';
$countries_str = "'".implode( "', '", $countries )."'"; // Formatting countries for jQuery
?>
<script type="text/javascript">
(function($){
var required = '<abbr class="required" title="<?php echo $required; ?>">*</abbr>',
countries = [<?php echo $countries_str; ?>],
location = $('#billing_country option:selected').val(),
cityCheck = 'input#billing_city_check';
function actionRequire( actionToDo='yes', selector='' ){
if ( actionToDo == 'yes' ) {
$(selector).addClass("validate-required");
$(selector+' label').append(required);
} else {
$(selector).removeClass("validate-required");
$(selector+' label > .required').remove();
}
$(selector).removeClass("woocommerce-validated");
$(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
}
// Default value when loading
actionRequire( 'no','#billing_city_check' );
if( $.inArray( location, countries ) >= 0 && $(cityCheck).val() == '0' ){
actionRequire( 'yes','#billing_city_check' );
$(cityCheck).val('1');
}
// Live value
$( 'form.checkout' ).on( 'change', '#billing_country', function(){
var location = $('#billing_country option:selected').val();
if ( $.inArray( location, countries ) >= 0 && $(cityCheck).val() == 0 ) {
actionRequire( 'yes','#billing_city_check' );
$(cityCheck).val('1');
} else if ( $(cityCheck).val() == 1 ) {
actionRequire( 'no','#billing_city_check' );
$(cityCheck).val('0');
}
});
})(jQuery);
</script>
<?php
}
// City validation, when it's visible
add_action('woocommerce_checkout_process', 'billing_city_field_process');
function billing_city_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['billing_city'] && $_POST['billing_city_check'] == '1' )
wc_add_notice( __( 'Please enter city.' ), 'error' );
}
【问题讨论】:
标签: php wordpress woocommerce