Coding with SPIP 3.0
SPIP3.0 Technical Documentation

> > > > Forcing the language of the visitor’s choice

Forcing the language of the visitor’s choice

The parameter forcer_lang

The #MENU_LANG form stores the selected language in a cookie. This cookie can then be used to re-display the site in the language that the user has chosen. One of the ways of doing this is to define the forcer_lang global variable in the options file.

  1. $GLOBALS['forcer_lang'] = true;

Specifying this parameter indicates to SPIP that it should systematically redirect a requested page by adding the lang URL parameter with the language cookie value if there is one, and if not, then with the code of the site’s main language.

This forcer_lang global code, however, also has another action: at the same time, it specifies that the language strings of the interface should display in the visitor’s language, and not in the language assigned to the articles and sections.

Another use of the cookie

Another possibility is to use the user’s preference, but not to force the redirection through the lang URL parameter, but rather by using SPIP’s set_request function to add a calculated lang parameter that SPIP will later reuse when it calls the _request function.

Example

The example below, used in an options file, calculates the language to be used. This calculation is made in two steps:

  • check if the URL is of the form http://name.domain/language/rest_of_the_url, where "language" is one of the languages defined for the site ("fr", "en" or "es" for example) and in such a case, use the language thus discovered,
  • otherwise, the utiliser_langue_visiteur() function uses the cookie language, otherwise use the language of the browser.

And finally, if the language calculated is different from the cookie, then the cookie is recreated.

  1. // Systematically add the context original language.
  2. if (!$langue = _request('lang')) {
  3. include_spip('inc/lang');
  4. $langues = explode(',', $GLOBALS['meta']['langues_multilingue']);
  5. // if the language is defined in the url (en/ or fr/), then use it
  6. if (preg_match(',^' . $GLOBALS['meta']['adresse_site'] . '/(' . join('|',$langues) . ')/,', 'http://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], $r)) {
  7. $langue = $r[1];
  8. changer_langue($langue);
  9. } else {
  10. $langue = utiliser_langue_visiteur();
  11. if (!in_array($langue, $langues)) {
  12. //$langue = "en"; // pour ne pas s'embeter !
  13. $langue = $GLOBALS['meta']['langue_site'];
  14. }
  15. }
  16. // store it in $_GET
  17. set_request('lang', $langue);
  18. }
  19.  
  20. // store the language as a cookie...
  21. if ($langue != $_COOKIE['spip_lang']) {
  22. include_spip('inc/cookie');
  23. spip_setcookie('spip_lang', $langue);
  24. }

Download

  • Author :
  • Published :
  • Updated : 27/06/10
  • Translations : English, français