Save last language preference of the user in a Cookie

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.

Read More

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

Related posts

Leave a Reply

2 comments

  1. 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

    localStorage.setItem(key, value);
    

    and afterwards to view the value, use

    localStorage.getItem(key);
    

    localStorage has a few advantages vs. cookies. Some of them are:

    • Cookies are included with every HTTP request, thereby slowing down your website by sometimes needlessly transmitting the same data over and over
    • Cookies are included with every HTTP request, thereby sending data unencrypted over the internet
    • Cookies are limited to about 4 KB of data
  2. 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.

    function init_language() {
        // this function called when no language has been defined yet
        var lang = getcookie( 'language' );
        if ( lang == 'hebrew' ) hebrew_pls();
    }
    
    function switch_language() {
       // When the user takes action to change language, ie, clicks a flag icon
       if ( selected_language == 'hebrew' ) hebrew_pls();
    }
    
    function hebrew_pls() {
       set_language('hebrew'); // aka, whatever you want to do
       setcookie( 'language', 'hebrew', 30 ); // remember the language for 30 days
    }
    

    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).

    /*
      setCookie( name, value, days, [path = "/"] )
        Sets a cookie, expires after "days" have passed
    
      getCookie( name, default )
        Gets the value of a cookie, or returns "default". Note: Does not set the cookie to default.
    */
    
    function setCookie(c_name, value, exdays, path) {
      var exdate = new Date();
      exdate.setDate(exdate.getDate() + exdays);
      var c_value = escape(value) + ((exdays == null) ? "" : ("; expires=" + exdate.toUTCString()));
      document.cookie = c_name + "=" + c_value + ((path == null) ? "; path=/" : "; path=" + path);
    }
    
    function getCookie(c_name, c_default) {
      var i, x, y, ARRcookies = document.cookie.split(";");
      for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^s+|s+$/g, "");
        if (x == c_name) {
          return unescape(y);
        }
      }
    
      if (typeof c_default != 'undefined') return c_default;
      return false;
    }