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';.
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.