我是 WordPress 开发新手。 我正在尝试在我的 WordPress 网站中创建基于位置的重定向。这个想法是根据用户所在的位置将用户从通用页面发送到与他相关的特定页面。我需要精确到美国的城市级别。 由于某种原因,我遇到了一些问题:
这是我想出的代码(加上用于调试目的的错误日志记录):
<?php
function redirect_based_on_location()
{
$ipAddress = $_SERVER['REMOTE_ADDR'];
// Log IP Address picked up by the server
error_log("$ipAddress");
// Log to detect if the function is called
error_log('Checking redirection conditions.');
// Check if on a specific page
if (is_page(2)) {
error_log('On page ID 2.');
// Check if the GeoIP Detection plugin is active
if (function_exists('geoip_detect2_get_info_from_current_ip')) {
$userInfo = geoip_detect2_get_info_from_current_ip();
if ($userInfo && $userInfo->city) {
$cityName = $userInfo->city->name;
error_log('Detected city: ' . $cityName);
// Prepare the URL mapping based on the city
$urlMapping = array(
'San Francisco' => 'https://example.com/sf',
'St. Louis' => 'https://example.com/stl',
'Kansas City' => 'https://example.com/kc'
);
// Check if the city is in the array and redirect
if (array_key_exists($cityName, $urlMapping)) {
error_log('Redirecting to: ' . $urlMapping[$cityName]);
wp_redirect($urlMapping[$cityName]);
exit;
} else {
error_log('City not in redirection list.');
}
} else {
error_log('GeoIP detection failed or city not available.');
}
} else {
error_log('GeoIP Detection plugin is not active or available.');
}
} else {
error_log('Not on page ID 2.');
}
}
add_action('template_redirect', 'redirect_based_on_location');
以下是我将 VPN 设置为圣路易斯并仅刷新页面一次时收到的日志示例:
[23-Apr-2024 19:21:02 UTC] 172.71.254.146
[23-Apr-2024 19:21:02 UTC] Checking redirection conditions.
[23-Apr-2024 19:21:02 UTC] On page ID 2.
[23-Apr-2024 19:21:02 UTC] Detected city:
[23-Apr-2024 19:21:02 UTC] City not in redirection list.
[23-Apr-2024 19:21:05 UTC] 172.71.254.29
[23-Apr-2024 19:21:05 UTC] Checking redirection conditions.
[23-Apr-2024 19:21:05 UTC] Not on page ID 2.
所以问题是:
如果相关的话。我的网站托管在 Namecheap 上,我也使用 Cloudflare。 谢谢!
function redirect_based_on_location() { if (!defined('REDIRECT_CALLED')) { define('REDIRECT_CALLED', true); // Your existing code here... } }
关于不同的 IP 地址,可能是由于 VPN 服务或您的服务器处理 IP 地址检测的方式所致。由于网络配置或代理设置的原因,您的服务器记录的 IP 地址可能并不总是与外部服务报告的 IP 地址匹配。
这种差异可能是由于您的服务器检测 IP 地址的方式造成的。使用 VPN 时,实际的 IP 地址可能会被屏蔽或通过不同的服务器进行隧道传输,这可能会影响服务器看到的 IP 地址。此外,某些 VPN 服务可能使用动态 IP 分配,因此 IP 地址可能会频繁更改。
IP 地理定位并不总是 100% 准确,尤其是在城市级别。 GeoIP 数据库的准确性、VPN 服务的质量以及代理服务器的存在等多种因素都会影响检测到的位置的准确性。然而,对于大多数实际用途,IP 地理定位可以提供相当准确的结果。
为了提高基于位置的重定向的准确性,您可以考虑使用更可靠的 IP 地理定位服务,例如 APILayer 的 ipstack,它提供准确且最新的地理位置数据。您可以将 ipstack API 集成到您的 WordPress 网站中,以根据 IP 地址检索位置信息,然后相应地重定向用户。与使用免费的 GeoIP 数据库或插件相比,这种方法应该提供更可靠的结果。