我想替换http://www.wpfetish.com/ip2nation.php/?ip=具有http://ipinfo.io/yourip_here/country
在此代码中获取国家代码
/*Uses WordPress HTTP Class*/
if( !class_exists( 'WP_Http' ) )
include_once( ABSPATH . WPINC. '/class-http.php' );
$request = new WP_Http;
/*
* get country info based on the ip of user
* requests to the plugin server for ip to country code
*/
$result = $request->request( "http://www.wpfetish.com/ip2nation.php/?ip=$user_ip" );
if(!empty($result['body'])){
$res = json_decode($result['body']);
if($res->status == 'success'){
return strtoupper( $res->iso_code_2 );
}
}
return 'default';
}
您需要更改一些其他内容,因为http://ipinfo.io不返回正文或状态字段:
$ curl ipinfo.io/8.8.8.8
{
"ip": "8.8.8.8",
"hostname": "google-public-dns-a.google.com",
"city": "Mountain View",
"region": "California",
"country": "US",
"loc": "37.3860,-122.0838",
"org": "AS15169 Google Inc.",
"postal": "94040"
}
如果您只请求/country
,它不会返回JSON对象:
$ curl ipinfo.io/8.8.8.8/country
US
所以你需要的完整代码就是:
$request = new WP_Http;
$result = $request->request("http://ipinfo.io/$user_ip/country");
return trim($result);
如果你不想使用WP_Http,并且想检查一些特定的国家/地区,下面是完整的代码:
$user_ip = $_SERVER['REMOTE_ADDR'];
$res = file_get_contents("http://ipinfo.io/${user_ip}/country");
$country = trim($res);
if(in_array($country, array("GB", "US"))) {
// User is in the UK or US
}
只需替换代码中的URL值,注意不要丢失引号,然后进行测试。