2

I am making a plugin to display estimate shipping/delivery time depend on visitor IP address. To do this I am using WC_Geolocation but using this I can get only visitor country code like US CA etc how can I get visitor state name if county is US .

 $geoData   = WC_Geolocation::geolocate_ip();
 $country   = $geoData['country'];
 echo $country;

will output country code. how to get state name?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Firefog
  • 3,094
  • 7
  • 48
  • 86

1 Answers1

5

To get the geolocated state:

// Get an instance of the WC_Geolocation object class
$geo_instance  = new WC_Geolocation();
// Get geolocated user geo data.
$user_geodata = $geo_instance->geolocate_ip();

// Get current user GeoIP Country
$country = $user_geodata['country'];

// Get current user GeoIP State
$state   = isset($user_geodata['state']) ? $user_geodata['state'] : '';
   
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • how can i find which array key contain $user_geodata like `country` `state` etc – Firefog Aug 13 '18 at 10:44
  • if you use `print_r($user_geodata)` or `var_dump($user_geodata)` you will see that you get an array of `country` + `state` … – LoicTheAztec Aug 13 '18 at 10:48
  • 1
    Thanks you save my day – Firefog Aug 13 '18 at 10:49
  • @LoicTheAztec i want to use this in my custom plugin. so i write your code in my custom plugin file and then echo $country. then i am not getting country code . when i write print_r($geo_instance); then i am getting WC_Geolocation Object ( ) – Abilash Erikson Apr 05 '22 at 06:44