Reputation: 143
I'm trying to make a multi-regional website using WordPress. i'm working on url http://localhost/siteone I want when someone come from usa redirect to the localhost/siteone/usa/ I edit the function.php file of wordpress theme with code below, but getting error the url become localhost/siteone/usa/usa/usa/usa
// Detacting user location using ipstack
$json = file_get_contents('http://api.ipstack.com/check?access_key=ACCESSKEY&language=en');
// Converts it into a PHP object
$data = json_decode($json);
$loc = $data->country_code;
//NA = northamerica
//End of Decating user location
if($loc=="NA"){ header("Location: usa/"); }
This works very well sidealone but when I add in function.php in theme file not working and give me a error. what should I do. Should i use some session or anything eles.
Upvotes: 0
Views: 232
Reputation: 33
For languages and create diferents regionals website, I'd recommend you this plugins (pro):
Custom code based on language:
<?php
if(pll_current_language() == 'en') {
echo 'Only in english';
} else if(pll_current_language() == 'fr') {
echo 'Seulment en francais';
}
?>
If you prefer control language throught web server, use better: $_SERVER['HTTP_ACCEPT_LANGUAGE']
Link: https://www.php.net/manual/en/locale.acceptfromhttp.php
Regards!
Upvotes: 1
Reputation: 640
It looks like it's trying to redirect multiple times, since it'll check the person's location, then redirect, then after redirecting it'll check again, and redirect again, etc.
What you could do is check whether "/usa" is already in the page URL, and if not, redirect, something like this could work:
if ($loc === "NA" && strpos($_SERVER['REQUEST_URI'],'usa/') === false) {
header("Location: usa/");
}
$_SERVER['REQUEST_URI'] is the URL of the current page, not including the domain.
Upvotes: 1