Skip to content

Instantly share code, notes, and snippets.

@ScottDeLuzio
Created November 3, 2017 17:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ScottDeLuzio/9689ff4b08f2bbf80a57fc91b6d45986 to your computer and use it in GitHub Desktop.
Save ScottDeLuzio/9689ff4b08f2bbf80a57fc91b6d45986 to your computer and use it in GitHub Desktop.
Format and validate postal codes for Poland in WooCommerce
<?php
/* This will "normalize" the postcode entered by the customer, if the country seleced is Poland.
* Normalize meaning that it doesn't matter if they entered the post code as xx-xxx or xxxxx the
* function will be able to format it correctly. Once a "normalized" postcode is generated, the
* function will add a hyphen (-) in between the 2nd and 3rd numbers in the post code.
* This will always generate a xx-xxx formatted postcode.
*/
add_filter( 'woocommerce_format_postcode', 'sd_add_poland_post_code_format', 10, 2 );
function sd_add_poland_post_code_format( $postcode, $country ){
$postcode = wc_normalize_postcode( $postcode );
switch ( $country ) {
case 'PL' :
$postcode = trim( substr_replace( $postcode, '-', 2, 0 ) );
break;
}
return $postcode;
}
/* This will validate the postcode entered by the customer and returned by the function above if the
* country selected is Poland. This function checks to see if the post code is formatted as two characters
* between 0-9, a hyphen, then three characters between 0-9.
* If this check passes, the function will return 'true', otherwise it will return 'false'.
*/
add_filter( 'woocommerce_validate_postcode', 'sd_validate_poland_post_code', 10, 3 );
function sd_validate_poland_post_code( $valid, $postcode, $country ){
switch ( $country ) {
case 'PL':
$valid = (bool) preg_match( '/^([0-9]{2})(-[0-9]{3})?$/i', $postcode );
break;
}
return $valid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment