Removing Content Types From Drupal Search Results

Often when building a Drupal site, we create content types that should only be displayed in a specific context. For instance if you create a content type for billboards that you only want displayed in a slider, you do not want your site visitors to view a billboard via it's direct node path. Obviously if you do not want people to see this you would not link to it, however, there will still be links to these nodes in your search results. You can remove these content types from your search results using the Search Configuration module, but if you're like me and prefer to not add additional overhead if you don't need to, you can add the following code to your theme's template.php file or in a custom module. This snippet will alter Drupal's search query and remove any content types that you do not want returned.


/** * Implements hook_query_alter(). * removes content types defined in the excluded_content_types array from search results */ function hook_query_alter(&$query) { $is_search = FALSE; $excluded_content_types = array( 'product', 'billboard', ); foreach ($query->getTables() as $table) { if ($table['table'] == 'search_index') { $is_search = TRUE; } } if ($is_search) { foreach ($excluded_content_types as $content_type) { $query->condition('n.type', $content_type, '<>'); } } }

Tags: Drupal 7