Drupal search results in current language

When you have multiple languages enabled on your drupal site and you have search enabled, you will want to have the search results displayed in the current language.

Here is a nice little snippet that helps out a bunch:

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, '=');

Together with the custom_search module this snippet makes sure the current language is displayed in the search results


Thanks for your code. I made a custom module based on it but get the following error when

Recoverable fatal error: Argument 1 passed to lang_search_query_node_access_alter() must be an instance of QueryAlterableInterface, instance of Drupal\Core\Database\Driver\mysql\Select given, called in /www/core/lib/Drupal/Core/Extension/ModuleHandler.php on line 501 and defined in lang_search_query_node_access_alter() (line 16 of /www/sites/all/modules/lang_search/lang_search.module).

Any hints on how search api may have changed in Drupal 8.1?

Hi Gerald,

This code was made for Drupal 7. I know they changed a lot of stuff on the search components in Drupal 8.
I don't have much experience with D8 yet. 


Good luck with your module. 

Add new comment