I want to make a WooCommerce Postcode Checkout Field that only required when the country is not saudi Arabia . This field should only be required when the customer chose a country other then saudi arabia
But it doesn't work
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);');
The following will do the job, making WooCommerce postcode Checkout Field required only when the country is not Saudi Arabia:
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;
}
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.