Using Argument from Function to Re-Direct Visitor (WordPress)
After googling around and reading, I found the code below. Problem is, it’s been a few weeks and I’ve lost the original post.
I have now done my best in understanding how to create a function hooked into template_redirect
so that I can re-direct visitors based on the country they are from.
I understand that this is not bullet-proof and what not, but it’s the best working solution I found that does not require a paid plugin.
This is the IP and Country function:
function visitor_ip_and_country() {
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
$country = "Unknown";
if ( filter_var( $client, FILTER_VALIDATE_IP ) ) {
$ip = $client;
}
elseif ( filter_var( $forward, FILTER_VALIDATE_IP ) ) {
$ip = $forward;
} else {
$ip = $remote;
}
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "http://www.geoplugin.net/json.gp?ip=".$ip);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );
$ip_data_in = curl_exec( $ch )
curl_close( $ch );
$ip_data = json_decode( $ip_data_in, true );
$ip_data = str_replace( '"', '"', $ip_data );
if ( $ip_data && $ip_data['geoplugin_countryName'] != null ) {
$country = $ip_data['geoplugin_countryName'];
}
return 'IP-address: '.$ip.' | Country: '.$country;
}
I have then tried to create a function that re-directs users, but I keep getting an "undefined variable" error.
Here is that code:
add_action( 'template_redirect', 'redirect_canadians' );
function redirect_canadians() {
$redirect = '';
$vc = visitor_ip_and_country($country);
if ($vc == 'Canada') {
$redirect = 'https://example.com';
wp_redirect($redirect);
die();
}
}
It refers to this line:
$vc = visitor_ip_and_country($country);
I don’t know how to get the re-direct function to check the argument from the visitor_ip_and_country()
function.
I need help.
Leave an answer