wordpress屏蔽某个国家访问代码
- 编程技术
- 2024-08-15
- 10932

为什么要用代码?因为插件装多了wordpress会慢,而且很多插件也不太好用。 function block_countries( { &...
为什么要用代码?因为插件装多了wordpress会慢,而且很多插件也不太好用。
function block_countries(){
$location = WC_Geolocation::geolocate_ip();
$country = $location['country'];
$blocked_countries = array('CN','US'); // 这里列出你想要屏蔽的国家代码,可以根据需要添加或修改
if ( in_array($country, $blocked_countries) ){
wp_die('抱歉,本站暂不对您的国家开放访问!');
}
}
add_action('wp_head','block_countries');将上边的代码添加到后台的外观-主题文件编辑器-functions.php文件。
上边的代码默认屏蔽了中国和美国,如果你想屏蔽其他国家,只需要填写其他国家的代码就可以了
还有要注意的是,这个代码是基于本身你的wordpress安装了Woocommerce插件才能实现的。
如果你没安装woocommerce插件,那就需要用到一下代码了。
将下面的代码添加到wordpress后台的外观-主题文件编辑器-functions.php文件:
function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
$output = NULL;
if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
$ip = $_SERVER["REMOTE_ADDR"];
if ($deep_detect) {
if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
}
$purpose = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
$support = array("country", "countrycode", "state", "region", "city", "location", "address");
$continents = array(
"AF" => "Africa",
"AN" => "Antarctica",
"AS" => "Asia",
"EU" => "Europe",
"OC" => "Australia (Oceania)",
"NA" => "North America",
"SA" => "South America"
);
if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {
$ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {
switch ($purpose) {
case "location":
$output = array(
"city" => @$ipdat->geoplugin_city,
"state" => @$ipdat->geoplugin_regionName,
"country" => @$ipdat->geoplugin_countryName,
"country_code" => @$ipdat->geoplugin_countryCode,
"continent" => @$continents[strtoupper($ipdat->geoplugin_continentCode)],
"continent_code" => @$ipdat->geoplugin_continentCode
);
break;
case "address":
$address = array($ipdat->geoplugin_countryName);
if (@strlen($ipdat->geoplugin_regionName) >= 1)
$address[] = $ipdat->geoplugin_regionName;
if (@strlen($ipdat->geoplugin_city) >= 1)
$address[] = $ipdat->geoplugin_city;
$output = implode(", ", array_reverse($address));
break;
case "city":
$output = @$ipdat->geoplugin_city;
break;
case "state":
$output = @$ipdat->geoplugin_regionName;
break;
case "region":
$output = @$ipdat->geoplugin_regionName;
break;
case "country":
$output = @$ipdat->geoplugin_countryName;
break;
case "countrycode":
$output = @$ipdat->geoplugin_countryCode;
break;
}
}
}
return $output;
}
function block_cn(){
$block_cn = ip_info($ip, "Country");
//echo $ip;
//echo '<hr>'.$block_cn.'<hr>';
if($block_cn == 'China'){
wp_die('本站不对中国访客开放!');
}
}
add_action('wp_head','block_cn');本文由卡卡于2024-08-15发表在卡卡博客,如有疑问,请联系我们。
本文链接:https://www.tuiedu.org/128.html
本文链接:https://www.tuiedu.org/128.html
上一篇:php跳转代码,第四版(已测)