Show the Distance in Miles for US based Visitors and in Kilometers for Everyone Else

If your store locations are spread around the world, and you’d like US-based visitors to see the distance in miles instead of kilometers, follow the directions in this article.

All code used throughout this article needs to go in the functions.php inside your active theme folder.

  1. Determine the IP of the current visitor
  2. Find the country the IP is located in
  3. Set the correct distance unit based on the users country

Determine the IP of the current visitor

The first part of the code looks up the IP of the current visitor. We need this information to determine the country the user is located in through an IP Geolocation API.

Find the country the IP is located in

In the next part we send the collected IP to a service called https://ipstack.com/ to find the country the IP is from.

To use this service you need to signup for a free API key. The free plans comes with 10.000 API Calls a month.

Once you have the API key you need to set it on line 9 in the code below. So replace $api_key = ''; with $api_key = 'xxxxx';.

Caching

To prevent making lots of request for the same IP, the returned country code is stored in the db cache for 30 minutes. If you’d like to change this, then you can do so on line 12. The value it takes is in seconds, so 1800 is 30 minutes.

Set the correct distance unit based on the user’s country

The last couple of lines determine whether to use ‘km’ or ‘mi’ based on the returned country code. The returned ‘km’ or ‘mi’ value is used in the search radius dropdown, the search results template, and in the SQL query that calculates the actual distance between the location the user provided and the store locations in the database.

All three code examples need to go in the functions.php in your active theme folder.

If you’ve enabled the “Load locations on page load” option on the settings page, then make sure to flush the transient cache.