Ask your WordPress questions! Pay money and get answers fast! (more info)

Simple function to redirect based on country code WordPress

  • SOLVED


Hello,

I'm struggling to get any of my code to work, and I want to avoid using a plugin.

Working answer gets full prize.


---------


<strong>The Brief</strong>

I need a function to go in my functions.php to redirect visitors by country code to another address.

I only need to do it for one country with is Italy IT

But if the visitor is not based in Italian territory - then I need the redirect function to do absolutely nothing.

if ( $countyCode = 'IT' ) {
header 'Location: http://www.mysite.it';
}


Can anyone help put something together?

I will test by changing the country code to my county code.



Many thanks
Josh

Answers (3)

2013-03-13

Nilesh shiragave answers:


<?php

$meta = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR']));

if($meta['geoplugin_countryCode']=='IT')
{
}
?>


You can check more details about the geo location API at http://www.geoplugin.com/webservices/php


Josh Cranwell comments:

Thanks for your code.

I just tried putting this in my functions.php and it do nothing?


$meta = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR']));
if ($meta['geoplugin_countryCode']=='EN') {
header('Location: http://mysite.co.uk');
}


Nilesh shiragave comments:

Where you added that code?

<?php
$meta = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip='.$_SERVER['REMOTE_ADDR']));

echo '<pre>';
print_r($meta);
echo '</pre>';

if ($meta['geoplugin_countryCode']=='EN') {

header('Location: http://mysite.co.uk');

}
?>

Add those three lines to print all the geo location data. and check what you get for geoplugin_countryCode


Josh Cranwell comments:

This is the simple answer that I was after! Perfect!

I printed the results and the count code being return was GB for Great Britain.

I was using EN for england.


Thanks for you answer!

2013-03-13

Agus Setiawan answers:

you can use this plugin http://codecanyon.net/item/wp-geoip-country-redirect/3589163

2013-03-13

Daniel Yoen answers:

Please try this : http://stackoverflow.com/questions/2832380/how-do-i-track-the-visitors-country-and-redirect-them-to-appropriate-sites

Hope this help :-)