WC_Shipping_Zone_Data_Store::get_zone_id_from_package()publicWC 3.0.0

Find a matching zone ID for a given package.

Method of the class: WC_Shipping_Zone_Data_Store{}

Hooks from the method

Return

Int.

Usage

$WC_Shipping_Zone_Data_Store = new WC_Shipping_Zone_Data_Store();
$WC_Shipping_Zone_Data_Store->get_zone_id_from_package( $package );
$package(object) (required)
Package information.

Changelog

Since 3.0.0 Introduced.

WC_Shipping_Zone_Data_Store::get_zone_id_from_package() code WC 9.4.2

public function get_zone_id_from_package( $package ) {
	global $wpdb;

	$country   = strtoupper( wc_clean( $package['destination']['country'] ) );
	$state     = strtoupper( wc_clean( $package['destination']['state'] ) );
	$continent = strtoupper( wc_clean( WC()->countries->get_continent_code_for_country( $country ) ) );
	$postcode  = wc_normalize_postcode( wc_clean( $package['destination']['postcode'] ) );

	// Work out criteria for our zone search.
	$criteria   = array();
	$criteria[] = $wpdb->prepare( "( ( location_type = 'country' AND location_code = %s )", $country );
	$criteria[] = $wpdb->prepare( "OR ( location_type = 'state' AND location_code = %s )", $country . ':' . $state );
	$criteria[] = $wpdb->prepare( "OR ( location_type = 'continent' AND location_code = %s )", $continent );
	$criteria[] = 'OR ( location_type IS NULL ) )';

	// Postcode range and wildcard matching.
	$postcode_locations = $wpdb->get_results( "SELECT zone_id, location_code FROM {$wpdb->prefix}woocommerce_shipping_zone_locations WHERE location_type = 'postcode';" );

	if ( $postcode_locations ) {
		$zone_ids_with_postcode_rules = array_map( 'absint', wp_list_pluck( $postcode_locations, 'zone_id' ) );
		$matches                      = wc_postcode_location_matcher( $postcode, $postcode_locations, 'zone_id', 'location_code', $country );
		$do_not_match                 = array_unique( array_diff( $zone_ids_with_postcode_rules, array_keys( $matches ) ) );

		if ( ! empty( $do_not_match ) ) {
			$criteria[] = 'AND zones.zone_id NOT IN (' . implode( ',', $do_not_match ) . ')';
		}
	}

	/**
	 * Get shipping zone criteria
	 *
	 * @since 3.6.6
	 * @param array $criteria Get zone criteria.
	 * @param array $package Package information.
	 * @param array $postcode_locations Postcode range and wildcard matching.
	 */
	$criteria = apply_filters( 'woocommerce_get_zone_criteria', $criteria, $package, $postcode_locations );

	// Get matching zones.
	return $wpdb->get_var(
		"SELECT zones.zone_id FROM {$wpdb->prefix}woocommerce_shipping_zones as zones
		LEFT OUTER JOIN {$wpdb->prefix}woocommerce_shipping_zone_locations as locations ON zones.zone_id = locations.zone_id AND location_type != 'postcode'
		WHERE " . implode( ' ', $criteria ) // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		. ' ORDER BY zone_order ASC, zones.zone_id ASC LIMIT 1'
	);
}