我想创建一个 WooCommerce 邮政编码结帐字段,仅当该国家/地区不是沙特阿拉伯时才需要。仅当客户选择沙特阿拉伯以外的国家/地区时,才需要填写此字段
但是没用
function woocommerce_no_postcode(array $fields): array
{
// bail if the country is not SA
if (!isset($_POST['billing_country']) || 'SA' === $_POST['billing_country']) {
return $fields;
}
$fields['billing']['postcode']['required'] = true;
return $fields;
}
add_filter('woocommerce_checkout_fields', 'woocommerce_no_postcode', 10, 1);');
以下内容将完成这项工作,仅当国家/地区不是沙特阿拉伯时才需要 WooCommerce 邮政编码结帐字段:
add_filter( 'woocommerce_get_country_locale', 'custom_country_locale_postcode', 10, 1 );
function custom_country_locale_postcode( $locale ) {
foreach ( $locale as $country => $data ){
$locale[$country] = array( 'postcode' => array(
'required' => true,
) );
}
$locale['SA'] = array( 'postcode' => array(
'required' => false,
) );
return $locale;
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。