我正在编写一个脚本,以检测用户是否离我们的位置足够近,从而显示位于子域上的网站的本地版本。我正在寻求帮助,我应该插入这一点和从WordPress重定向的最佳方法
<?php
$ip = $_SERVER[\'REMOTE_ADDR\'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
$clean = substr($details->loc, 0, -1);
$coord = explode(\',\', $clean);
$latitudeFrom = floatval($coord[0]);
$longitudeFrom = floatval($coord[1]);
echo "Long: ".$longitudeFrom."\\r\\n";
echo "Lat: ".$latitudeFrom."\\r\\n";
$longitudeTo = -68.6833;
$latitudeTo = 33.1711;
$radius = 50; //miles
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$latDelta = $latTo - $latFrom;
echo $latDelta."\\r\\n";
$lonDelta = $lonTo - $lonFrom;
echo $lonDelta."\\r\\n";
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
$distance = $angle * 3959;
if ($distance < $radius) {
//redirect to local page
}
?>
SO网友:czerspalace
在函数中。您的主题的php文件,我将添加一个挂钩到template\\u redirect的操作,如下所示(未测试):
<?php
add_action( \'template_redirect\', \'wpse251614_redirect_to_local_site\' );
function wpse251614_redirect_to_local_site(){
$ip = $_SERVER[\'REMOTE_ADDR\'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
$clean = substr($details->loc, 0, -1);
$coord = explode(\',\', $clean);
$latitudeFrom = floatval($coord[0]);
$longitudeFrom = floatval($coord[1]);
echo "Long: ".$longitudeFrom."\\r\\n";
echo "Lat: ".$latitudeFrom."\\r\\n";
$longitudeTo = -68.6833;
$latitudeTo = 33.1711;
$radius = 50; //miles
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$latDelta = $latTo - $latFrom;
echo $latDelta."\\r\\n";
$lonDelta = $lonTo - $lonFrom;
echo $lonDelta."\\r\\n";
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
$distance = $angle * 3959;
if ($distance < $radius) {
//redirect to local page
wp_redirect(LOCAL_PAGE);
exit;
}
}
?>
参考号:
https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirecthttps://developer.wordpress.org/reference/functions/wp_redirect/