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

The module Search Restrict is based on this technique.

Tags: ,,