Drupal 8: Filter content types in core search

Published by Lennart Van Vaerenbergh on December 19, 2018

It appears there is no plug & play solution to filter out certain content types from the Drupal 8 core search. I tried the module search_exclude but at the moment of writing it's not working as it should.
There is a simple solution but it requires a custom module. Add the following snippet to a custom module in your project:
 
use Drupal\Core\Database\Query\AlterableInterface;

/**
 * Implements hook_query_TAG_alter().
 */
function my_module_query_search_node_search_alter(AlterableInterface $query) {
  // Only show article and blogpost content in the search results.
  $query->condition('n.type', ['article', 'blogpost'], 'IN');
}
In the example above, only the content type 'article' and 'blogpost' are displayed in the search results.
Obviously don't forget to change the 'my_module' part to your own custom module name. That's it!

Add new comment

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.
CAPTCHA
This challenge is for testing whether or not you are a human visitor and to prevent automated spam submissions.