Hi,
I'd like to also return an excerpt from the field which matched.
<?php namespace Processwire;
/**
* Search.
*
* Global site search.
*
* @author snipped.
* @version 1.0.0
*/
// Retrieve the GET request.
$query = $sanitizer->text($input->get->query);
if (!$query) {
return;
}
// Sanitise the user input.
$query = $sanitizer->selectorValue($query);
// Instantiate the Search object.
new Search($query);
/**
* Search.
*
* Return results from matching pages.
*
* @param query
*/
class Search {
protected $query;
protected $excludedFieldTypes;
protected $templates;
protected $matches;
protected $output;
public function __construct($query) {
$this->query = $query;
$this->excludedFieldTypes = ['FieldtypeImage', 'FieldtypeSelect', 'FieldtypeMediaManager', 'FieldtypeFieldsetTabOpen', 'FieldtypeFieldsetClose', 'FieldtypeRepeater', 'FieldtypeCheckbox', 'FieldtypeModule', 'FieldtypePassword'];
$this->templates = $this->getTemplates();
$this->matches = $this->getMatches();
$this->renderResults();
}
/**
* getTemplates
*
* Return an array of templates & fields to be searched.
*
* @return pages
*/
public function getTemplates() {
$templates = [];
foreach (wire('templates') as $template) {
$fields = [];
foreach ($template->fields as $field) {
// Exclude certain field types.
if (in_array($field->type, $this->excludedFieldTypes)) {
continue;
}
array_push($fields, $field);
}
// Turn the array to a string suitable for the API.
$fields = implode("|", $fields);
$templates[$template->name] = [
'template' => $template->name,
'fields' => $fields,
];
}
return $templates;
}
/**
* getMatches
*
* Return an array of matching pages.
*
* @return matchingPages
*/
public function getMatches() {
$matches = [];
foreach ($this->templates as $template) {
$selector = "template=" . $template['template'] . ", " . $template['fields'] . "%=$this->query";
$results = wire('pages')->find($selector);
foreach ($results as $result) {
array_push($matches, $result);
}
}
return $matches;
}
/**
* renderResults
*
* Render the results of the search.
*/
public function renderResults() {
if (!$this->matches) {
echo 'No results.';
return;
}
foreach ($this->matches as $match) {
$this->output .= '<p>' . $match->title . '</p>';
$this->output .= '<p>' . $match->url . '</p>';
$this->output .= '<p>' . $match->field . '</p>';
}
echo $this->output;
}
}
/**
* debug
*
* Helper method for visualising arrays.
*/
function debug($variable) {
echo '<pre>';
print_r($variable);
echo '<pre>';
}