I’m running a WordPress Multisite Installation with two languages: Hebrew and English.
I have a plugin called Geo IP that helps me to redirect users based on their IP country.
But actually I need more.
I would like to save the last language the user choose.
Example :
if a user close the tab of my site on the english language, I would like that when he comes back, he’ll get the english language. Vice versa for Hebrew.
I’m not a pro developer, but I think a cookie can be a solution, and I would like the solution to be in JS if possible.
Update: the code I made ! WDYT guys ?
function get_language {
var myLang = getcookie ('language');
if ( myLang == 'hebrew') {
window.location = "http://zeek.me/he/";
}
else if ( myLang == 'english') {
window.location = "http://zeek.me";
}
else {
window.location = "http://zeek.me";
}
}
function set_language(lang) {
var setLang = setcookie ('language', lang, 30);
var englishClick = document.getElementById('#english_lang');
var hebrewClick = document.getElementById('#hebrew_lang');
englishClick.addEventListener('click', function() {
set_language('english');
})
hebrewClick.addEventListener('click', function() {
set_language('hebrew');
})
}
What you guys think ?
Any solution ?
Thanks,
Simon
As you want a solution with Javascript, you should consider the localStorage. Cookies are nice if you want to know the selected language server-side, but if you just need it local, localStorage is better (reasons below).
To set a localStorage item, use
and afterwards to view the value, use
localStorage has a few advantages vs. cookies. Some of them are:
Sounds pretty basic, cookies are what you want. You can stick with javascript, or use php cookies. You opted for a javascript solution.
You’ll need a few functions to make this work. Here are some examples below, but these are not working code. You’ll need to edit them to do the language switching.
Here are the cookie functions I’ve been using for awhile. It’s based on “How do I create and read a value from cookie?“. I have modified these so they are a bit easier to use. If you don’t like my modifications, there are plenty of alternatives online. Unfortunately JavaScript does not have an easy way to store cookies by default (without third party plugins/scripts).