Hi @ameliaakh
I hear you. It’s a bummer that the Belgium zip/postal code validation is not available in the WooCommerce core by default.
I checked WooCommerce core and found the relevant lines of code that adds this feature: https://github.com/woocommerce/woocommerce/blob/d20d429e3264798fbfd5335e971f1e46531cf7bb/includes/class-wc-validation.php#L40-L108
As seen here, the woocommerce_validate_postcode
hook can be used to manipulate these validation rules.
Based on this, I prepared a quick code snippet that should help you in achieving your requirement:
add_filter('woocommerce_validate_postcode','woo_validate_belgium_postcode',10,3);
function woo_validate_belgium_postcode($valid, $postcode, $country){
if($country=="BE")
$valid = (bool) preg_match( '/^([0-9]{4})$/', $postcode );
// Checks your postcode to seee if it matches belgium (4 digits). If not, it will reject validation.
return $valid;
}
I’d recommend adding it to your site using a Code Snippets Plugin, even though you can always add code snippets like this to the bottom of your theme’s functions.php
. (The downside of this approach is that your code gets lost in plugin/theme updates).
When you add this PHP code to your site, WooCommerce will only accept four-digit zip codes when you select Belgium as the country. As you can see in the following screenshot, it rejects the 1011AM
zip code from your example: https://d.pr/i/J3ci41
I hope this helps.