Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Created March 19, 2020 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igorbenic/c5e962734dbf23553569ce4c319a4438 to your computer and use it in GitHub Desktop.
Save igorbenic/c5e962734dbf23553569ce4c319a4438 to your computer and use it in GitHub Desktop.
How to use the WooCommerce Postcode Validator | https://www.ibenic.com/woocommerce-postcode-validator
<?php
/**
* Used by shipping zones and taxes to compare a given $postcode to stored
* postcodes to find matches for numerical ranges, and wildcards.
*
* @since 2.6.0
* @param string $postcode Postcode you want to match against stored postcodes.
* @param array $objects Array of postcode objects from Database.
* @param string $object_id_key DB column name for the ID.
* @param string $object_compare_key DB column name for the value.
* @param string $country Country from which this postcode belongs. Allows for formatting.
* @return array Array of matching object ID and matching values.
*/
function wc_postcode_location_matcher( $postcode, $objects, $object_id_key, $object_compare_key, $country = '' ) {
$postcode = wc_normalize_postcode( $postcode );
$wildcard_postcodes = array_map( 'wc_clean', wc_get_wildcard_postcodes( $postcode, $country ) );
$matches = array();
foreach ( $objects as $object ) {
$object_id = $object->$object_id_key;
$compare_against = $object->$object_compare_key;
// Handle postcodes containing ranges.
if ( strstr( $compare_against, '...' ) ) {
$range = array_map( 'trim', explode( '...', $compare_against ) );
if ( 2 !== count( $range ) ) {
continue;
}
list( $min, $max ) = $range;
// If the postcode is non-numeric, make it numeric.
if ( ! is_numeric( $min ) || ! is_numeric( $max ) ) {
$compare = wc_make_numeric_postcode( $postcode );
$min = str_pad( wc_make_numeric_postcode( $min ), strlen( $compare ), '0' );
$max = str_pad( wc_make_numeric_postcode( $max ), strlen( $compare ), '0' );
} else {
$compare = $postcode;
}
if ( $compare >= $min && $compare <= $max ) {
$matches[ $object_id ] = isset( $matches[ $object_id ] ) ? $matches[ $object_id ] : array();
$matches[ $object_id ][] = $compare_against;
}
} elseif ( in_array( $compare_against, $wildcard_postcodes, true ) ) {
// Wildcard and standard comparison.
$matches[ $object_id ] = isset( $matches[ $object_id ] ) ? $matches[ $object_id ] : array();
$matches[ $object_id ][] = $compare_against;
}
}
return $matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment