Reputation: 1659
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?
Upvotes: 0
Views: 2515
Reputation: 118
You can do it directly as:
const currentLanguage = document.documentElement.lang;
Upvotes: 1
Reputation: 96
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');
}
Upvotes: 4
Reputation: 578
I'm not very familiar with wordpress, but usually languages are set right after the domain name or as a url parameter. The function below handles both cases.
// tested with the following urls:
// url = 'domain.com/sdfsdf/dafsfd?lang=es';
// url = 'domain.com/sdfsdf/dafsfd?lang=es&sdfsf=dfsdf';
// url = 'domain.com/en-uk';
// url = 'domain.com/en-uk/';
// url = 'domain.com/en-uk?dfsdfsdf=dfsdf&sdfsfsdf=dfsdfs';
var url = window.location.href;
var lang = getLanguage(url);
console.log(lang);
function getLanguage(url) {
// if language is set via url parameter
if (url.includes('?lang=')) {
return url.split('?lang=')[1].split('&')[0];
}
// if language is set via url route
else {
return url.split('/')[1].split('?')[0];
}
}
Upvotes: 1