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.

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

// Systematically add the context original language.
if (!$langue = _request('lang')) {
	include_spip('inc/lang');
	$langues = explode(',', $GLOBALS['meta']['langues_multilingue']);
	// if the language is defined in the url (en/ or fr/), then use it
	if (preg_match(',^' . $GLOBALS['meta']['adresse_site'] . '/(' . join('|',$langues) . ')/,', 'http://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], $r)) {
		$langue = $r[1];
		changer_langue($langue);
	} else {	
		$langue = utiliser_langue_visiteur();
		if (!in_array($langue, $langues)) {
			//$langue = "en"; // pour ne pas s'embeter !
			$langue = $GLOBALS['meta']['langue_site'];
		}
	}
	// store it in $_GET
	set_request('lang', $langue);
}

// store the language as a cookie...
if ($langue != $_COOKIE['spip_lang']) {
	include_spip('inc/cookie');
	spip_setcookie('spip_lang', $langue);
}

Author Mark Baber Published : Updated : 12/03/23

Translations : English, français, Nederlands