Drupal 7 – Exclude node type in search results
Websites that use the search of Drupal 7 core have now ability to restrict the search and exclude some node types for example. I see some articles that Drupal 8 probably will have this kind of functionality.
However, it’s possible to rewrite the SQL query that selects the search results. Thanks to the Drupal database layer this can be done quite easily.
/**
* Excludes node type "foo" from search results
*
* @param object $query
*/
function mymodule_query_alter(&$query) {
$is_search = FALSE;
foreach ($query->getTables() as $table) {
if ($table['table'] == 'search_index') {
$is_search = TRUE;
}
}
if ($is_search) {
$query->condition('n.type', 'foo', '<>');
}
}
* Excludes node type "foo" from search results
*
* @param object $query
*/
function mymodule_query_alter(&$query) {
$is_search = FALSE;
foreach ($query->getTables() as $table) {
if ($table['table'] == 'search_index') {
$is_search = TRUE;
}
}
if ($is_search) {
$query->condition('n.type', 'foo', '<>');
}
}
The module Search Restrict is based on this technique.
This works great but I might consider not hardcoding the alias so this works for as many queries as possible.
$is_search = FALSE;
foreach ($query->getTables() as $table) {
if ($table['table'] == 'search_index') {
$is_search = TRUE;
}
if ($table['table'] == 'node') {
$node_alias = $table['alias'];
}
}
if ($is_search) {
$exclusions = array('audio', 'callout', 'country', 'downloadable_media', 'news', 'job_source', 'slide', 'timeline_event');
foreach ($exclusions as $type) {
$query->condition($node_alias . '.type', $type, '<>');
}
}
}