Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save unofficialshopify/460e39e5df04b85890bfe83d6b0bdef3 to your computer and use it in GitHub Desktop.
Save unofficialshopify/460e39e5df04b85890bfe83d6b0bdef3 to your computer and use it in GitHub Desktop.
How to get a visitor’s location and redirect them to right store for Shopify
These days some business have online store in different country with the same name. They have different URL for different country but they are facing a problem that how they can redirect store url based on IP address for eg.
www.domain.us – Customers in the United States
www.domain.ca – Customers in the Canada
www.domain.com – Customers in rest the world
This article guide you to do that.
We use service of Freegeoip.net (Freegeoip) to detected visitor’s location. Freegeoip provides a public HTTP API for software developers to search the geolocation of IP addresses. This is the code.
jQuery.getJSON('//freegeoip.net/json/', function(location) {
});
location is the result returned. It includes: IP, country_code, country_name, region_code, region_name, city, zip_code, time_zone, latitude, longitude, metro_code.
We need country code (country_code) information. You can compare with country codes table at here to know more.
Now we write code to redirect.
In site’s United States
jQuery.getJSON('//freegeoip.net/json/', function(location) {
if(location.country_code != 'US'){
if(location.country_code == 'CA'){
location.href = "//www.domain.ca";
}else{
location.href = "//www.domain.com";
}
}
});
In site’s Canada
jQuery.getJSON('//freegeoip.net/json/', function(location) {
if(location.country_code != 'CA'){
if (location.country_code == 'US'){
location.href = "//www.domain.us";
}else{
location.href = "//www.domain.com";
}
}
});
and site’s rest the world
jQuery.getJSON('//freegeoip.net/json/', function(location) {
if(location.country_code == 'US'){
location.href = "//www.domain.us";
} else if(location.country_code == 'CA'){
location.href = "//www.domain.ca";
}
});
@pablomlozano
Copy link

Hello.
Thanks for this info.
Could you please let me know where to place this piece of code on Shopify?
Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment