All Collections
How-tos
How to detect current selected language?
How to detect current selected language?
Edvard avatar
Written by Edvard
Updated over a week ago

If you want to code something special for individual language you can detect the current selected language and write your code based on that.

Note: This article is intended for persons with technical skills. If you have problems, you can ask our Live chat agents for help, we might be able to provide some limited help.

Detecting current language for Free version

For GTranslate free version the code of the current selected language is stored in googtrans cookie. It can be something like /en/es, which means that the page is translated from English to Spanish. You can get the code of the current selected language with JavaScript using the following piece of code:

/*
* If original language is selected, then the value of current_language
* will be empty. Otherwise, it will contain the current selected
* language code.
*
*/
var current_language = gt_get_cookie('googtrans').split('/').pop();

// W3 Schools: https://www.w3schools.com/js/js_cookies.asp
function gt_get_cookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

Detecting current language for paid versions

For GTranslate paid versions you can find the code of the current selected language from X-GT-Lang request header or from <html> lang attribute.

Below you can see an example of detecting the code of the current selected language with PHP:

/*
* If original language is selected, then the value of $current_language
* will be empty. Otherwise, it will contain the current selected
* language code.
*
*/
$current_lang = isset($_SERVER['HTTP_X_GT_LANG']) ? $_SERVER['HTTP_X_GT_LANG'] : '';

// To avoid caching of the original content
header('Cache-Control: no-cache');

Alternatively you can use JavaScript:

/*
* If original language is selected, then the value of current_language
* will be the lang attribute of your original page. Otherwise, it will
* contain the current selected language code.
*
*/
var current_lang = document.getElementsByTagName('html')[0].getAttribute('lang');

Did this answer your question?