0

I'm developing a website and I'm using WPML to create different languages on the website. I would like to Geo redirect users based on their countries.

I'm using subdirectories in WPML so I have:

www.mydomain.com

www.mydomain.com/ie/

www.mydomain.com/ca/

I created a script that allows me to get the IP and get a country's code into a variable (this is what I'm using), I also created a header redirect with this script. This is what I put in my functions.php file:

add_action ('wp_loaded', 'my_redirect_function');

function my_redirect_function() {

  $ip = '';

     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'];
     }

     $country = file_get_contents('http://geoip.maxmind.com/a?l=6QT6fNSdtMVw&i='.$ip);

     if( $country == 'IE' ) {

         wp_redirect( get_bloginfo('url') . "/ie/" );

         exit;

     }

}

I don't know why I get an endless loop.

1
  • You don't need to run my_redirect_function() again when already redirected to the language directory. Check referrer or directory you are in.
    – Max Yudin
    Commented Jan 17, 2018 at 10:47

1 Answer 1

1

Your code redirects to "/ie/" also if you are already on "/ie/". The easiest way to prevent this is by changing

if( $country == 'IE' ) {

to

if( $country == 'IE' && substr( $_SERVER['REQUEST_URI'], 0, 4 ) != '/ie/' ) {
2
  • Thanks a lot for the answer, I tried to change it, now I don't get the endless loop but I'm not redirected anymore. when I type "www.mydomain.com" I'm not redirected to "www.mydomain.com/ie", any idea?
    – Crashy
    Commented Jan 17, 2018 at 11:15
  • That was my mistake sorry. I used the wrong logical operator. It has to be != instead of ==. I corrected my code
    – ahendwh2
    Commented Jan 17, 2018 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.