The problem is the variable $sountry
– and this is because of something called variable scope – https://www.php.net/manual/en/language.variables.scope.php – the variable is only available within the function, as you do not “export” it or make it globally available – here is an update to your functions to show how this might work:
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 array(
'ip' => $ip,
'country' = >$country
// note, you could add additional keys to this array
);
}
add_action( 'template_redirect', 'redirect_canadians' );
function redirect_canadians() {
// call your function to get an array with IP and country values ##
$array = visitor_ip_and_country();
$redirect="";
$vc = $array['country'];
if ($vc == 'Canada') {
$redirect="https://example.com";
wp_redirect($redirect);
die();
}
}
This is a simple solution, get it working, then refine it more.