Add language switcher to Toolbar

Having a lot of Canadian clients, we end up creating a lot of sites which require switching between French and English. Recently, I had to add the language switcher to the default Toolbar module where the username/login/logout links appear. Here’s how I did it.

Step 1

First, ensure you have at least two languages installed. But due to the limited real estate on the toolbar, try to not have more than 3 or 4 languages.

Step2

Next, go to your theme and add entry in your template.php file for the following preprocess hook


/**
 * Implements template_preprocess_toolbar().
 */
function mytheme_preprocess_toolbar(&$variables) {
  // Fill in code here
}

We’re going to add to the “toolbar_user” links array to render the language switch links. (see http://api.drupal.org/api/drupal/modules!toolbar!toolbar.tpl.php/7 for more info)

Step 3

Next we need to load the list of available languages, eliminate the one we’re currently viewing (for space saving purposes) and prepend the links to the toolbar_user array. Here’s what code looks like.


/**
 * Implements template_preprocess_toolbar().
 */
function mytheme_preprocess_toolbar(&$variables) {

  // Add language switcher to toolbar_user section
  if (drupal_multilingual()) {
    global $language;
    include_once DRUPAL_ROOT . '/includes/language.inc';
    $info = language_types_info();
    
    $lang_types = language_types_configurable(FALSE);
    
    $path = drupal_is_front_page() ? '' : $_GET['q'];
        
    foreach($lang_types as $type) {
      $languages = language_negotiation_get_switch_links($type, $path);

      if (isset($languages->links)) {
        foreach($languages->links as $lang => $link) {
          if ($lang != $language->language) {
            array_unshift($variables['toolbar']['toolbar_user']['#links'], $link);
          }
        }
      }
    }
  }
}

If you’d like to show the currently selected language, just remove the if statement checking the $lang against the current language value.

In the end, you should have the language switch links just in front of the username in the Toolbar.