Drupal - Search only for the currently active language

There's a really elegant way to do this using the apparently undocumented hook_query_node_access_alter():

function yourmodule_query_node_access_alter(QueryAlterableInterface $query) {
  $search = FALSE;
  $node = FALSE;

  // Even though we know the node alias is going to be "n", by checking for the
  // search_index table we make sure we're on the search page. Omitting this step will
  // break the default admin/content page.
  foreach ($query->getTables() as $alias => $table) {
    if ($table['table'] == 'search_index') {
      $search = $alias;
    }
    elseif ($table['table'] == 'node') {
      $node = $alias;
    }
  }

  // Make sure we're on the search page.
  if ($node && $search) {
    $db_and = db_and();
    // I guess you *could* use global $language here instead but this is safer.
    $language = i18n_language_interface();
    $lang = $language->language;

    $db_and->condition($node . '.language', $lang, '=');
    $query->condition($db_and);
  }
}

Note: this code is 100% based on the excellent Search Config module.

User's vs Content language

Some sites might have language detection configured to show the interface in the user's preferred language, while the page content is shown based on the URL or content language.

In that case, consider replacing

$language = i18n_language_interface();

with

$language = i18n_language_content();

I had the same requirements, and I used the Custom search module, which includes a submodule called Custom Search Internationalization : "search content from all or current language only, and all label and selectors translation handling" (note this module provides also several other helpful features like custom search blocks). Works perfectly.


You can use the global $language to know in which language you are. In Views, you can filter using "content:language -> current user language."