Free IP Geo Location on WPEngine

WPEngine recently started offering the ability to geolocate IP’s if you’re on the business plan or above. But for many of you still on the personal plan this is no help. If you have a low traffic site (less than 1000 visitors a day) then this could be a good solution for you. Put this at the top of your functions.php file:

if(!isset($_COOKIE['loc'])) {
    $daysToExpiry = 30; // The amount of days the cookie is good for
    $response = file_get_contents(''.$_SERVER['REMOTE_ADDR']);
    $response = json_decode($response);
    setcookie('loc', $response->country, time()+($daysToExpiry*24*60*60), '/');

Now you have access to $_COOKIE['loc'] which will contain the 2 character country code of your visitor. also provides some other data in the response that you could use as well. Here’s a typical resonse:

  "ip": "",
  "hostname": "",
  "city": "Mountain View",
  "region": "California",
  "country": "US",
  "loc": "37.3860,-122.0838",
  "org": "AS15169 Google Inc.",
  "postal": "94035"

20% Off WP Engine