wc_get_customer_geolocation()
Uses geolocation to get the customer country and state only if they are valid values.
No Hooks.
Returns
Array.
Usage
wc_get_customer_geolocation( $fallback, foooo, ) );
- $fallback(array)
- Fallback location.
Default: array( foo - foooo
- .
Default: > fooooo - )(required)
- .
Changelog
| Since 9.5.0 | Introduced. |
wc_get_customer_geolocation() wc get customer geolocation code WC 10.3.5
function wc_get_customer_geolocation( $fallback = array(
'country' => '',
'state' => '',
) ) {
$ua = wc_get_user_agent();
// Exclude common bots from geolocation by user agent.
if ( stripos( $ua, 'bot' ) !== false || stripos( $ua, 'spider' ) !== false || stripos( $ua, 'crawl' ) !== false ) {
return $fallback;
}
$geolocation = WC_Geolocation::geolocate_ip( '', true, false );
if ( empty( $geolocation['country'] ) ) {
return $fallback;
}
// Ensure geolocation is valid.
$allowed_countries = WC()->countries->get_allowed_countries();
if ( ! isset( $allowed_countries[ $geolocation['country'] ] ) ) {
return $fallback;
}
$allowed_states = WC()->countries->get_allowed_country_states();
$country_states = $allowed_states[ $geolocation['country'] ] ?? array();
if ( $country_states && ! isset( $country_states[ $geolocation['state'] ] ) ) {
$geolocation['state'] = '';
}
return array(
'country' => $geolocation['country'],
'state' => $geolocation['state'],
);
}