大多数情况下,通过使用IP地址和geoIP服务,大多数人都可能获得非常模糊的位置信息。我说“模糊”是因为你经常得到的是ISP服务器的位置,而不是特定IP地址的具体位置。例如,在家里,我的IP被列为距离我实际所在的位置大约30-40英里。此外,有些人可能通过代理进行访问,而代理可能距离他们的实际位置数百或数千英里。如果这些是可接受的参数,那么类似于。。。
$IP = $_SERVER[\'REMOTE_ADDRESS\'];
// get location data
// I am using freegeoip.net for this
// I can\'t vouch for the service. It is just an example,
// but I queried my IP and it worked well.
$location = wp_remote_get("http://freegeoip.net/json/{$IP}");
// var_dump($location);
// location information is in $location[\'body\']
// check status
if (\'200\' == $location[\'response\'][\'code\']) {
$geoloc = json_decode($location[\'body\']);
var_dump($geoloc);
// and you get this
// stdClass Object
// (
// [city] => xxx
// [region_code] => xx
// [region_name] => xx
// [metrocode] => xxx
// [zipcode] => xxxxx
// [longitude] => xxxxxx
// [latitude] => xxxxxx
// [country_code] => xx
// [ip] => xxx.xxx.xxx.xxx
// [country_name] => xxxxx
// )
// you know have what you need to switch your homepage content
}
免费IP。net将请求限制为每小时1000个,因此请注意仅在必要时运行代码--设置一个cookie之类的东西。我推荐
caching the data 减少请求数量并减少联系第三方服务的开销/延迟。