✨ Professional WordPress development, custom website builder, efficient on-line, cooperate and enjoy optimization services! 🚀
GeoIP2
Database Download:Click to download
aboutConfiguration of the GeoIP Detection plug-in can be found in the documentation.
PHP to set the visitor's country Cookie (recommended to put into functions.php)
add_action('init', function () {
if (is_admin() || is_user_logged_in()) return; if (isset($_COOKIE['geoip_country'])) return;
if (isset($_COOKIE['geoip_country'])) return; return;
if (!function_exists('geoip_detect2_get_info_from_current_ip')) return; return;
$record = geoip_detect2_get_info_from_current_ip();
if (!empty($record->country->isoCode)) {
setcookie('geoip_country', $record->country->isoCode, time() + 86400, '/');
}
});
Second, JS: according to the cookie quickly jump to the corresponding language page (hidden jump, without pop-up window)
<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>
caveat
-
Make sure you have enabled and configured GeoIP Detection plug-inUse
GeoIP2
Database. -
If you are using a CDN (such as Cloudflare), you need to enable real IP delivery, otherwise you will get the IP of the CDN node.
-
This jump logic does not affect visitors who are already in the correct language path and does not interfere with search engine indexing.
If you can't solve it, you can contact us to help you integrate it!