wc_postcode_location_matcher()WC 2.6.0

Used by shipping zones and taxes to compare a given $postcode to stored postcodes to find matches for numerical ranges, and wildcards.

No Hooks.

Return

Array. Array of matching object ID and matching values.

Usage

wc_postcode_location_matcher( $postcode, $objects, $object_id_key, $object_compare_key, $country );
$postcode(string) (required)
Postcode you want to match against stored postcodes.
$objects(array) (required)
Array of postcode objects from Database.
$object_id_key(string) (required)
DB column name for the ID.
$object_compare_key(string) (required)
DB column name for the value.
$country(string)
Country from which this postcode belongs. Allows for formatting.
Default: ''

Changelog

Since 2.6.0 Introduced.

wc_postcode_location_matcher() code WC 8.7.0

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;
}