✨专业 WordPress 开发,定制建站,高效上线,合作即享优化服务!🚀
GeoIP2
数据库下载:点击下载
关于GeoIP Detection 插件的配置,可自行查阅资料。
一、PHP 设置访客国家 Cookie(推荐放入 functions.php)
add_action('init', function () {
if (is_admin() || is_user_logged_in()) return;
if (isset($_COOKIE['geoip_country'])) return;
if (!function_exists('geoip_detect2_get_info_from_current_ip')) return;
$record = geoip_detect2_get_info_from_current_ip();
if (!empty($record->country->isoCode)) {
setcookie('geoip_country', $record->country->isoCode, time() + 86400, '/');
}
});
二、JS:根据 Cookie 快速跳转对应语言页面(隐藏跳转,无需弹窗)
<script>
document.addEventListener("DOMContentLoaded", function () {
if (sessionStorage.getItem('geoip_lang_redirected')) return;
const match = document.cookie.match(/(?:^|;\s*)geoip_country=([^;]+)/);
const countryCode = match ? match[1] : null;
if (!countryCode) return; // 未获取国家,跳过
const langMap = {
GB: '', // 英文默认
US: '',
CN: 'zh',
HK: 'zh-hk',
SA: 'ar',
NL: 'nl',
FR: 'fr',
DE: 'de',
JP: 'ja',
IT: 'it',
ES: 'es',
HU: 'hu',
FY: 'fy',
KZ: 'kk',
TR: 'ku',
LT: 'lt',
MK: 'mk',
IR: 'fa',
PK: 'sd',
SI: 'sl',
IN: 'ta',
TH: 'th'
};
const defaultLang = 'zh'; // 默认语言路径(当国家未匹配时)
const langSlug = langMap[countryCode] !== undefined ? langMap[countryCode] : defaultLang;
const currentPath = window.location.pathname.replace(/\/+$/, '');
const langPrefix = langSlug ? `/${langSlug}` : '';
const alreadyInLang = langSlug && (currentPath === langPrefix || currentPath.startsWith(langPrefix + '/'));
if (alreadyInLang) return;
sessionStorage.setItem('geoip_lang_redirected', '1');
// 拼接当前路径并跳转(保留路径)
const newPath = langPrefix + currentPath;
window.location.href = newPath;
});
</script>
注意事项
-
确保你已启用并配置 GeoIP Detection 插件,使用
GeoIP2
数据库。 -
如果使用 CDN(如 Cloudflare),需开启真实 IP 传递,否则获取的是 CDN 节点的 IP。
-
此跳转逻辑不会影响已进入正确语言路径的访客,也不会干扰搜索引擎收录。
如果解决不了,可以联系我们帮您集成!