5

I am trying to change the Drupal's default language programmatically but haven't found the codes/function. Any suggestions?

  • 2
    At a guess... $langs = language_list('enabled'); variable_set('language_default', $langs[$some_langcode]); – Clive Jun 18 '14 at 11:13
  • @Clive, close, but not quite. See my answer for the correct code. – Free Radical Sep 25 '14 at 7:59
9

Here is a corrected and tested version of the code posted by @Clive in a comment to the OP:

$langs = language_list(); // Note: No argument
// debug($langs, '$langs');
$langcode = 'en';
variable_set('language_default', $langs[$langcode]);

The code snippet above assumes that the two-character code that you assign to $langcode is enabled. Uncomment the call to debug to see the languages that are enabled on your site and what array indices they use.

Note that the setting will not take effect until the next page load.

|improve this answer|||||
1

I have found the code and its pretty simple .

//Set Default language
    $default_language = array('language' => 'en-US', 
                            'name' => 'English', 
                            'native' => 'English', 
                            'direction' => LANGUAGE_LTR, 
                            'enabled' => (int) TRUE, 
                            'plurals' => 0, 
                            'formula' =>'',
                            'domain' => '', 
                            'weight' => 0, 
                            'javascript' => '');
variable_set('language_default', (object) $default_language) ;
|improve this answer|||||
0

By implementing the following hook: hook_language_negotiation_info() and here is a full example

http://tassaf.moriamedia.com/drupal-7-default-language-after-translation/

|improve this answer|||||
0

Just setting the variable is not always enough. By the time you've done so, the Drupal language negotiation function may have already run, and it will not react to this variable change. The proper way to do this is as follows:

// Get the list of languages
$languages = language_list();

// Set up the new language code
$new_lang_code = 'fr';

// Make sure the required language object is actually set
if (isset($languages[$new_lang_code])) {
  // Overwrite the global language object
  global $language;
  $language = $languages[$new_lang_code];
}

This has been documented in other questions such as: function to change language object

An additional option is to write your own custom language negotiation hook: https://api.drupal.org/api/drupal/modules!system!language.api.php/function/hook_language_negotiation_info/7

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.