Suggest the Visitor's Language Version
Shows a small, dismissible banner when the visitor's browser language differs from the page language and a translated version exists (read from the page's hreflang links), with a link to switch.
Opens WPIDE on
Code
<script>
(function () {
try { if (sessionStorage.getItem('wpideLangBanner')) { return; } } catch (e) {}
var pageLang = (document.documentElement.lang || '').toLowerCase().split('-')[0];
var wanted = (navigator.languages || [navigator.language || '']).map(function (l) { return l.toLowerCase(); });
var links = Array.prototype.slice.call(document.querySelectorAll('link[rel="alternate"][hreflang]'));
if (!pageLang || !links.length || wanted[0].split('-')[0] === pageLang) { return; }
var match = null;
wanted.some(function (w) {
match = links.filter(function (l) { var h = l.hreflang.toLowerCase(); return h === w || h.split('-')[0] === w.split('-')[0]; })[0];
return !!match;
});
if (!match || match.hreflang.toLowerCase().split('-')[0] === pageLang) { return; }
var name = match.hreflang;
try { name = new Intl.DisplayNames([match.hreflang], { type: 'language' }).of(match.hreflang) || name; } catch (e) {}
var bar = document.createElement('div');
bar.setAttribute('role', 'region');
bar.setAttribute('aria-label', 'Language');
bar.style.cssText = 'position:fixed;left:16px;right:16px;bottom:16px;max-width:480px;margin:0 auto;padding:12px 44px 12px 16px;background:#1d2327;color:#fff;border-radius:8px;z-index:99999;font:14px/1.4 system-ui,sans-serif;box-shadow:0 4px 16px rgba(0,0,0,.25)';
var a = document.createElement('a');
a.href = match.href;
a.lang = match.hreflang;
a.textContent = name + ' →';
a.style.color = 'inherit';
a.style.fontWeight = '600';
var close = document.createElement('button');
close.type = 'button';
close.setAttribute('aria-label', 'Close');
close.textContent = '×';
close.style.cssText = 'position:absolute;top:6px;right:8px;background:none;border:0;color:inherit;font-size:22px;cursor:pointer';
close.addEventListener('click', function () {
bar.remove();
try { sessionStorage.setItem('wpideLangBanner', '1'); } catch (e) {}
});
bar.appendChild(a);
bar.appendChild(close);
document.body.appendChild(bar);
})();
</script>
Notes
Works with WPML, Polylang or manual hreflang tags. Dismissal is remembered for the browser session; nothing redirects automatically.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.