WC_Geolocation::geolocate_ip( string $ip_address = '', bool $fallback = false, bool $api_fallback = true )
Geolocate an IP address.
Description Description
Parameters Parameters
- $ip_address
-
(Optional) IP Address.
Default value: ''
- $fallback
-
(Optional) If true, fallbacks to alternative IP detection (can be slower).
Default value: false
- $api_fallback
-
(Optional) If true, uses geolocation APIs if the database file doesn't exist (can be slower).
Default value: true
Return Return
(array)
Source Source
File: includes/class-wc-geolocation.php
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'],
);
}