Skip to main content

How do I filter search results in Drupal 8?Filter search results by language in Drupal 8

Actually the search module in Drupal 8 core doesn't currently display the results with the selected language.

After several searches, it is not possible to configure this in Drupal administration. There are two possible options available to us :

  1. Find a module that allows us to configure this
  2. Write a small module to modify the query generated for the search

We decided to create our module to solve this problem. 
This is how we proceeded :

  1. Create the module named "search_results_filter_by_lang" in the modules/custom directory. For more details on creating a module in Drupal 8 go here.
  2. Implementation of hook "hook_query_TAG_alter()" :  

    <?php 
    use Drupal\Core\Database\Query\AlterableInterface;

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

  3. Clear cache with the following command : drush cr
  4. Installation of the module


That's it, the search results are now filtered with the selected language. 
Be careful that this code cancels the search by language in the advanced search. This is not a problem for us because we don't allow advanced search for visitors (disable this via /admin/people/permissions). 

Étiquettes
Let's discuss your project

Contact us

  •  + 32 (0) 10 49 51 00
  •  info@expert-it.com