After trying to find a solution to this, I've decided I'm not bright enough. So, please help. Here the idea: have a file (ip.php) detect the visitors' country/city, call it once in functions.php (or header.php), then echo/print variables from this ip.php file into the other Wordpress theme files (for example footer.php). This is the ip.php content:
<?php
function getUserIP()
{
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
$_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
$user_ip = getUserIP();
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
$cityDbReader = new Reader('/html/nocache-ip/GeoLite2-City.mmdb');
$record = $cityDbReader->city($user_ip);
$country = $record->country->name;
?>
Using the following in the header.php works fine for the header:
require_once( ABSPATH . '/nocache-ip/ip.php' );
echo "\nYou came from $country\n";
The country, city names are displayed. But when trying to use the same code again in the footer.php, it doesn't work (Undefined variable: country).
So this is the issue. How can I make echo/print the visitor's country in other parts of the theme, while calling the ip.php only once? I've read about having to make all this into a function, then add it to functions.php somehow and then calling the variables with country(); unfortunately this is above my head.
You can use include so that your function is available, example:
<?php include 'yourfunctionpage.php';?>In your functions.php you declare a variable:
then in anotherfile.php you can use the variable from functions.php like this: