hook_search
Definition
hook_search($op = 'search', $keys = null)
developer/hooks/core.php, line 801
Description
Define a custom search routine.
This hook allows a module to perform searches on content it defines (custom node types, users, or comments, for example) when a site search is performed.
The example given here is for node.module, which uses the indexed search capabilities. To do this, node module also implements hook_update_index() which is used to create and maintain the index.
We call do_search() with the keys, the module name and extra SQL fragments to use when searching. See hook_update_index() for more information.
Parameters
$op A string defining which operation to perform:
- 'name': the hook should return a translated name defining the type of items that are searched for with this module ('content', 'users', ...)
- 'reset': the search index is going to be rebuilt. Modules which use hook_update_index() should update their indexing bookkeeping so that it starts from scratch the next time hook_update_index() is called.
- 'search': the hook should perform a search using the keywords in $keys
- 'status': if the module implements hook_update_index(), it should return
an array containing the following keys:
- remaining: the amount of items that still need to be indexed
- total: the total amount of items (both indexed and unindexed)
Return value
An array of search results. Each item in the result set array may contain whatever information the module wishes to display as a search result. To use the default search result display, each item should be an array which can have the following keys:
- link: the URL of the found item
- type: the type of item
- title: the name of the item
- user: the author of the item
- date: a timestamp when the item was last modified
- extra: an array of optional extra information items
- snippet: an excerpt or preview to show with the result (can be generated with search_excerpt())
Related topics
| Name | Description |
|---|---|
| Hooks | Allow modules to interact with the Drupal core. |
| Search interface | The Drupal search interface manages a global search mechanism. |
Code
<?php
function hook_search($op = 'search', $keys = null) {
switch ($op) {
case 'name':
return t('content');
case 'reset':
variable_del('node_cron_last');
return;
case 'search':
$find = do_search($keys, 'node', 'INNER JOIN {node} n ON n.nid = i.sid '. node_access_join_sql() .' INNER JOIN {users} u ON n.uid = u.uid', 'n.status = 1 AND '. node_access_where_sql());
$results = array();
foreach ($find as $item) {
$node = node_load(array('nid' => $item));
$extra = node_invoke_nodeapi($node, 'search result');
$results[] = array('link' => url('node/'. $item),
'type' => node_invoke($node, 'node_name'),
'title' => $node->title,
'user' => format_name($node),
'date' => $node->changed,
'extra' => $extra,
'snippet' => search_excerpt($keys, check_output($node->body, $node->format)));
}
return $results;
}
}
?> 