在WordPress中获取当前访客所在国家时区的方法
Hey there! Nice to see you're already leveraging geoplugin for visitor location data. Grabbing the visitor's timezone is super straightforward—you just need to pull the right field from the same geoplugin JSON response you're already using for the country code.
First, let me fix a couple of small issues in your original code (like the extra space in the URL and unnecessary POST request, since geoplugin's JSON endpoint uses GET) and add the timezone retrieval:
function getVisitorLocationData() { $ip = $_SERVER['REMOTE_ADDR']; $ch = curl_init(); $curlConfig = array( CURLOPT_URL => "http://www.geoplugin.net/json.gp?ip=".$ip, CURLOPT_RETURNTRANSFER => true, ); curl_setopt_array($ch, $curlConfig); $result = curl_exec($ch); curl_close($ch); // Handle potential request failures if (!$result) { return ['countryCode' => null, 'timezone' => null]; } $json_a = json_decode($result, true); // Safely extract values with fallback checks $countryCode = isset($json_a['geoplugin_countryCode']) ? $json_a['geoplugin_countryCode'] : null; $timezone = isset($json_a['geoplugin_timezone']) ? $json_a['geoplugin_timezone'] : null; return [ 'countryCode' => $countryCode, 'timezone' => $timezone ]; } // Usage example $visitorData = getVisitorLocationData(); echo "Country Code: " . $visitorData['countryCode'] . "<br>"; echo "Timezone: " . $visitorData['timezone'];
A few key notes here:
- I removed
CURLOPT_POST => truebecause the geoplugin JSON API expects a GET request—using POST would cause the request to fail. - Added basic error handling to cover cases where the curl request fails or the JSON can't be parsed.
- The timezone is pulled from the
geoplugin_timezonefield in the response, which gives you a standard IANA timezone identifier (likeEurope/LondonorAsia/Singapore).
If you just want a standalone function to get only the timezone, you can use this simplified version:
function getVisitorTimezone() { $ip = $_SERVER['REMOTE_ADDR']; $ch = curl_init(); $curlConfig = array( CURLOPT_URL => "http://www.geoplugin.net/json.gp?ip=".$ip, CURLOPT_RETURNTRANSFER => true, ); curl_setopt_array($ch, $curlConfig); $result = curl_exec($ch); curl_close($ch); if (!$result) { return null; } $json_a = json_decode($result, true); return isset($json_a['geoplugin_timezone']) ? $json_a['geoplugin_timezone'] : null; } // Usage example $timezone = getVisitorTimezone(); if ($timezone) { echo "Visitor Timezone: " . $timezone; } else { echo "Could not retrieve timezone."; }
That's all you need! If you run into any issues (like curl being disabled on your server), just let me know and we can troubleshoot alternatives.
内容的提问来源于stack exchange,提问作者Suresh Kumar

