每次访问我的网站时,都会根据他们的ip将用户重定向到一种语言,并在重定向后切换lang



我有一个Wordpress网站,它使用WPML for Multilang,我在网站上有三种语言,带有子目录选项(/fr、/en和/de(。

示例:如果用户在德国,我想将他重定向到"/de";并且仍然让他能够切换到另一种语言

我发现了一些插件,比如";IP2Location";但所有类似的插件都会将用户重定向到他当前的国家/地区语言,并且永远无法切换到另一种语言

我试着通过应用cookie来使用javascript,但这也有问题,它会每天重定向用户一次,而不是每次他们回到网站时

这里是它的最佳解决方案。您现在可以尝试它,它会起作用的。只需替换您的国家代码和网站url。

function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
add_action('wp', 'ak_redirect_on_ip_base');
function ak_redirect_on_ip_base()
{
$my_current_lang = apply_filters('wpml_current_language', NULL);
$xml = simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=" . getRealIpAddr());
// echo $xml->geoplugin_countryName;
//It will return country code
echo $xml->geoplugin_countryCode;

if ($xml->geoplugin_countryCode ==  'DE' && $my_current_lang != 'de') {
header('Location: http://www.youdomain.com/de');
} elseif ($xml->geoplugin_countryCode ==  'fr'  && $my_current_lang != 'fr') {
header('Location: http://www.youdomain.com/fr');
} else {
header('Location: http://www.youdomain.com/');
};
die;
}
//uncomment this code and see all the variable into this array to match best condition 
/*foreach ($xml as $key => $value) {
echo $key, "= ", $value,  " n";
}
echo "</pre>";
*/
?>

最新更新