WC_Geolocation::geolocate_ip()public staticWC 1.0

Geolocate an IP address.

Method of the class: WC_Geolocation{}

Return

Array.

Usage

$result = WC_Geolocation::geolocate_ip( $ip_address, $fallback, $api_fallback );
$ip_address(string)
IP Address.
Default: ''
$fallback(true|false)
If true, fallbacks to alternative IP detection (can be slower).
Default: false
$api_fallback(true|false)
If true, uses geolocation APIs if the database file doesn't exist (can be slower).
Default: true

WC_Geolocation::geolocate_ip() code WC 8.7.0

public static function geolocate_ip( $ip_address = '', $fallback = false, $api_fallback = true ) {
	// Filter to allow custom geolocation of the IP address.
	$country_code = apply_filters( 'woocommerce_geolocate_ip', false, $ip_address, $fallback, $api_fallback );

	if ( false !== $country_code ) {
		return array(
			'country'  => $country_code,
			'state'    => '',
			'city'     => '',
			'postcode' => '',
		);
	}

	if ( empty( $ip_address ) ) {
		$ip_address   = self::get_ip_address();
		$country_code = self::get_country_code_from_headers();
	}

	/**
	 * Get geolocation filter.
	 *
	 * @since 3.9.0
	 * @param array  $geolocation Geolocation data, including country, state, city, and postcode.
	 * @param string $ip_address  IP Address.
	 */
	$geolocation = apply_filters(
		'woocommerce_get_geolocation',
		array(
			'country'  => $country_code,
			'state'    => '',
			'city'     => '',
			'postcode' => '',
		),
		$ip_address
	);

	// If we still haven't found a country code, let's consider doing an API lookup.
	if ( '' === $geolocation['country'] && $api_fallback ) {
		$geolocation['country'] = self::geolocate_via_api( $ip_address );
	}

	// It's possible that we're in a local environment, in which case the geolocation needs to be done from the
	// external address.
	if ( '' === $geolocation['country'] && $fallback ) {
		$external_ip_address = self::get_external_ip_address();

		// Only bother with this if the external IP differs.
		if ( '0.0.0.0' !== $external_ip_address && $external_ip_address !== $ip_address ) {
			return self::geolocate_ip( $external_ip_address, false, $api_fallback );
		}
	}

	return array(
		'country'  => $geolocation['country'],
		'state'    => $geolocation['state'],
		'city'     => $geolocation['city'],
		'postcode' => $geolocation['postcode'],
	);
}