Search code examples
javascriptwordpresslocation

Wordpress: get page language in javascript


How to get the language of a Wordpress page in Javascript?

I have found a way to check for Spanish:

if(window.location.href.indexOf("/es/") > -1) {

But if the website is not with Permalink Settings with "Post name", the language preference will be with ?lang=es in the URL.

And, can a Wordpress lang preference be "en-uk" for example?


Solution

  • In principle a decent WordPress translation plugin would update the <html> tag with the apporpiate lang parameter, for instance, if language is set to American English:

    <html lang="en-US">
    ... page code
    </html>
    

    Therefore, I think it would be much simpler using this function:

    function getLanguage() {
        return document.getElementsByTagName('html')[0].getAttribute('lang');
    }