I'm developing a Wordpress plugin and am trying to use the following function to return a variable called $user_country that can be accessed in other functions in the same file. The code works when I nest it inside another function, but when I make it its own function, I can't access the variable $user_countryfrom other functions.
(I'm still new to PHP / coding and trying to learn and wouldn't be surprised if I'm making an obvious newbie mistake.)
function get_user_country() {
if (!class_exists('GeoIP')) {
include_once("geoip.inc");
}
if (empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$ip_address = $_SERVER["REMOTE_ADDR"];
} else {
$ip_address = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
if (!filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === FALSE) {
$gi = \LSMIGeoIP\geoip_open(WP_PLUGIN_DIR . "/location-specific-menu-items/GeoIP.dat", GEOIP_STANDARD);
$user_country = \LSMIGeoIP\geoip_country_code_by_addr($gi, $ip_address);
\LSMIGeoIP\geoip_close($gi);
} elseif (!filter_var($ip_address, FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) === FALSE) {
$gi = \LSMIGeoIP\geoip_open(WP_PLUGIN_DIR . "/location-specific-menu-items/V6GeoIP.dat", GEOIP_STANDARD);
$user_country = \LSMIGeoIP\geoip_country_code_by_addr($gi, $ip_address);
\LSMIGeoIP\geoip_close($gi);
} else {
$user_country = "Can't locate IP: " . $ip_address;
}
return $user_country;
}
global $user_countryinside a function to use global variables.global $user_country;but no change.include_once("geoip.inc");does not seem right. It should have a.phpextension.class_exists(GeoIP)should have quotes:class_exists('GeoIP')