Skip to content
Advertisement

redirect the users based on their ip to a language every time they visit my website with the ability to switch lang after redirection?

I have a WordPress site using WPML for Multilang, I have three languages on the site with subdirectories option ( /fr , /en , /de ).

Example: If a user is in Germany I want to redirect him to “/de” and still give him the ability to switch to another language

I found some plugins like “IP2Location” but all plugins like that keep redirecting the user to his current country language and never be able to switch to another language

I tried doing it with javascript by applying cookies but that have a problem too it will redirect users once a day and not every time they come back to the site

Advertisement

Answer

Here is the best solution for it. You can try it now it will be work. Just replace your country code and website 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>";
*/
?>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement