I am looking for help with coding a button so that when a visitor in the UK clicks on it, they are redirected to a UK specific page. If they are not in the UK, they are directed to the default EU page indicated in the Editor.
What I have so far is:
import wixLocation from 'wix-location';
import {fetch} from 'wix-fetch';
$w.onReady(function () {fetch('https://extreme-ip-lookup. com/json',
{method: 'get'}
})
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
}
})
.then((json) => {
// Set the user's countryCode as a const
const loc = json.countryCode;
/* Check if location is GB, and check if the visitor is not on GB Dogs page */
if(loc === "GB"){
// Redirect to GB Dog Food pages when buttons clicked
$w("#ShopDogs").onClick( (event) => {wixLocation.to("/uk-dog/dog-food")});
}})
At the moment, it is only directing to the default page, even when the IP is in the GB based.
First, you need your API key in there. You can generate your own key at the website you provided.
Then, you can simplify a little bit the code to become more readable, like so:
import wixLocation from 'wix-location'
import { fetch } from 'wix-fetch'
$w.onReady(async () => {
const locationFetch = await fetch(
'https://extreme-ip-lookup.com/json/?key=<API_KEY>'
) // you need your own API key there
const { countryCode } = locationFetch.ok ? await locationFetch.json() : false
/* Check if location is GB, and check if the visitor is not on GB Dogs page */
if (countryCode === 'GB') {
// Redirect to GB Dog Food pages when buttons clicked
$w('#ShopDogs').onClick(() => wixLocation.to('/uk-dog/dog-food'))
}
})
You could also just use the WIX Window API, and get the browserLocale property of the wixWindow and you would have some sort of location filtering (not as good as the Extreme IP Lookup though, but faster).
import wixWindow from 'wix-window'
$w.onReady(() => {
const { browserLocale } = wixWindow
if (browserLocale === 'en-GB') {
// Redirect to GB Dog Food pages when buttons clicked
$w('#ShopDogs').onClick(() => wixLocation.to('/uk-dog/dog-food'))
}
})
Thank you, thank you, thank you, Bruno!! I was trying to work off of someone’s tutorial and did not realize I needed an API key! An thank you for cleaning up the code. It is much clearer to me now. Thank you. 100% perfect!