Drupal - Search results only for the current language

The "Advanced" core search has this built in. If you prefer to do this from a theme - you could do it with form_alter. This basically hides the advanced search settings and sets current language as the only language to get results from, in the search block and search page.

Alternately you can just allow users to control which language they want to get results from and simply allow them to use advanced search.

Code for theme:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_search_form_alter(&$form, &$form_state) {
  $form['help_link']['#access'] = FALSE;
  $form['advanced']['#access'] = FALSE;
  $form['basic']['keys']['#title'] = '';
  $manager = \Drupal::languageManager();
  $form['advanced']['lang-fieldset']['language']['#default_value'] = [$manager->getCurrentLanguage()->getId()];
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function hook_form_search_block_form_alter(&$form, &$form_state) {
  $manager = \Drupal::languageManager();

  $form['advanced-form'] = [
    '#type' => 'hidden',
    '#value' => 1,
  ];
  $form['f[0]'] = [
    '#type' => 'hidden',
    '#value' => 'language:' . $manager->getCurrentLanguage()->getId(),
  ];
}

You can use simple way hook_query_TAG_alter. Example return node for current language.

<?php

use Drupal\Core\Database\Query\AlterableInterface;

/**
 * Implements hook_query_TAG_alter(): tag search_$type with $type node_search.
 */
function MYMODULE_query_search_node_search_alter(AlterableInterface $query) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $query->condition('n.langcode', $language, '=');
}

Tags:

Search

8