Last active
May 29, 2019 13:15
-
-
Save madeincosmos/215f33bdbb2825ed02694e24013a759d to your computer and use it in GitHub Desktop.
Add `F-` in front of French postcodes in WooCommerce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* This will "normalize" the postcode entered by the customer, if the country selected is France. | |
* If the customer entered their postcode as a 5-digit number, it will add `F-` in the front. | |
* If they already entered `F-` the post code will stay as it is. | |
*/ | |
add_filter( 'woocommerce_format_postcode', 'custom_add_post_code_format_for_france', 10, 2 ); | |
function custom_add_post_code_format_for_france( $postcode, $country ){ | |
$postcode = wc_normalize_postcode( $postcode ); | |
switch ( $country ) { | |
case 'FR' : | |
if ( (bool) preg_match( '/^F([0-9]{5})$/i', $postcode ) ) { | |
$postcode = trim( substr_replace( $postcode, '-', 1, 0 ) ); | |
} else if ( (bool) preg_match( '/^([0-9]{5})$/i', $postcode ) ) { | |
$postcode = trim( substr_replace( $postcode, 'F-', 0, 0 ) ); | |
} | |
break; | |
} | |
return $postcode; | |
} | |
/* This will validate the postcode entered by the customer and returned by the function above if the | |
* country selected is France. This function checks to see if the post code is formatted as | |
* `F-` followed by exactly 5 digits 0-9. | |
*/ | |
add_filter( 'woocommerce_validate_postcode', 'sd_validate_post_code_for_france', 10, 3 ); | |
function sd_validate_post_code_for_france( $valid, $postcode, $country ){ | |
switch ( $country ) { | |
case 'FR': | |
$valid = (bool) preg_match( '/^F-([0-9]{5})$/', $postcode ); | |
break; | |
} | |
return $valid; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment