WC_Shipping_Legacy_Local_Pickup::is_valid_postcode( string $postcode, string $country )

See if a given postcode matches valid postcodes.


Description Description


Parameters Parameters

$postcode

(Required) Postcode to check.

$country

(Required) code Code of the country to check postcode against.


Top ↑

Return Return

(boolean)


Top ↑

Source Source

File: includes/shipping/legacy-local-pickup/class-wc-shipping-legacy-local-pickup.php

	public function is_valid_postcode( $postcode, $country ) {
		$codes              = $this->get_valid_postcodes();
		$postcode           = $this->clean( $postcode );
		$formatted_postcode = wc_format_postcode( $postcode, $country );

		if ( in_array( $postcode, $codes, true ) || in_array( $formatted_postcode, $codes, true ) ) {
			return true;
		}

		// Pattern matching.
		foreach ( $codes as $c ) {
			$pattern = '/^' . str_replace( '_', '[0-9a-zA-Z]', preg_quote( $c ) ) . '$/i';
			if ( preg_match( $pattern, $postcode ) ) {
				return true;
			}
		}

		// Wildcard search.
		$wildcard_postcode = $formatted_postcode . '*';
		$postcode_length   = strlen( $formatted_postcode );

		for ( $i = 0; $i < $postcode_length; $i++ ) {
			if ( in_array( $wildcard_postcode, $codes, true ) ) {
				return true;
			}
			$wildcard_postcode = substr( $wildcard_postcode, 0, -2 ) . '*';
		}

		return false;
	}


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.