Drupal Custom search using hook_search



How to implement a custom search tab that searches a new content type using hook_search in Drupal CMS:


<?php
function mymodule_search($op 'search'$keys NULL) {
  switch(
$op) {
    
/**
     * Sets the tab
     */
    
case 'name':
      return 
t('name of the new tab');
    
/**
     * Defines the results
     */
    
case 'search':
      global 
$base_path;
      
// Change wildcards to SQL wildcard (+ will also act like * with this)
      
$keys preg_replace('!\*+!''%'$keys);

      
// Get all the data you need. Kept simple in this example
      
$sql "SELECT n.nid FROM {node} n, {node_revisions} nr WHERE (n.title LIKE '%%%s%%' OR nr.body LIKE '%%%s%%') AND n.nid = nr.nid";
      
$result db_query($sql$keys$keys);
      
$find = array();

      
// Runs through all database results to build the search results
      
while($nid db_result($result)) {
        
$node node_load($nid);
        
$link '/';
        switch(
$node->type) {
          case 
'mynodetype':
            
$link .= 'somepath/' $node->title// example link
            
$find[] = array('title' => $node->title'link' => $link'snippet' => search_excerpt($keys$node->teaser));
            break;
          case 
'anothernodetype':
            
$link .= 'anotherpath/' $node->nid;
            
$find[] = array('title' => $node->title'link' => $link'snippet' => search_excerpt($keys$node->teaser));
            break;
        }
      }
     
      
// Returns the results for display
      
return $find;
  }
}
?>