Perch documentation

Using Search

Perch contains the ability to search the content that you have added within Perch.

First make sure that you have copied into your site the search.php page from inside the Perch download and also the folder perch/templates/search and the template inside it.

As long as you have these in place you can get started with search by visiting search.php in your browser and searching for something that exists in your content.

It is worth knowing that by default Perch will use the URL of the page in the title field unless your template has something with title=“true” set on it. If I search for “test” I get the sidebar module content – this has a title because I have set title=“true” on this field. If search is important to you, using titles on fields can help optimise your results.

The search.php page is very simple the section which does all the work is:

<?php 
  if (isset($_GET['q'])) {
    $query = $_GET['q'];  
  }else{
    $query = '';
  } 
  perch_content_search($query); 
?>

So we read in the keywords from the QueryString and load perch_content_search() with either those keywords or an empty string.

Search calls in the template which is found at perch/templates/search. Open this up and we can have a look at what it is doing.

The first part of this template deals with what happens if there are results returned from a search. The elements in perch:before display the search form, which will repopulate with the keywords searched for.

We are checking for the existence of paging – which means there are more than 1 page of results – and showing the total results available.

We then loop through and display the results as a list item <li> element.

In the perch:after tags we display the paging if there is more than one page of results.

The bottom half of the template is contained within perch:noresults tags. There are two reasons why this page might load with no results. The first would be if the form hadn’t been submitted yet and the second would be if it had been submitted but the search returned nothing. We can check for this by looking to see if the keywords exist using perch:if exists. This template will display differently in each case.

You can customize this template by adding your own HTML, and of course everything can be styled using CSS as usual.

The perch_content_search function accepts an array of options and you can use this to customise the returned results. For example I can edit search.php to return only 3 results per page using count in an options array.

<?php 
  if (isset($_GET['q'])) {
    $query = $_GET['q'];  
  }else{
    $query = '';
  } 
  $opts = array(
    'count'=>3
  );
  perch_content_search($query,$opts); 
?>

Other options include passing in a custom template, changing the number of characters displayed in the excerpt and only searching in part of your site by passing in a path. Full details can be found in the search documentation.