I am working on a multilingual WordPress multisite. It has more than 10 languages. I created a javascript that will redirect between 2 languages. To do that I have used location.pathname to get the current page URL. Then I split it to get the last directory name. I have used the if condition to check if the current URL of the page is in the second language.
For example, if I am on a page www.xyz.com/fr/news and then if I change the language to english. It will redirect me to www.xyz.com/news. Now the problem is If I add third language I am unable to figure out what condition should I use to switch between different languages. for example, If I am on a page www.xyz.com/fr/news and I want to switch to German. It should redirect from www.xyz.com/fr/news to www.xyz.com/de/news.
Every redirection should load the current page in requested language.
HTML Code:
<a class="dropdown-item" onclick="myFunction()">English</a>
Below is a javacript code snippet to switch from the default language.
function myFunction() {
document.getElementById("fr").onclick = location.replace(
window.location.origin + "/" + fr" + "/"
);
document.getElementById("de").onclick = location.replace(
window.location.origin + "/" + "de" + "/"
);
}
And below is a javascript code snippet to switch from second languages to default one.
function myFunction() {
var pathname = window.location.pathname;
var lang = pathname.split("/")[1];
var page = pathname.split("/")[2];
if ((lang = "fr/")) {
location.replace(window.location.origin + "/" + page);
}
}
let page = window.location.pathname.split("/");This turns the URL into an Array that you can use later on with the [0], [1], etc.case 'fr': URL = xyz.url/frSome explanation can be found here: (w3schools.com/js/js_switch.asp)