How to define a “Sorry, no search matches” message in Textpattern

16. Januar 2006

Textpattern lacks a built-in tag that provides users with a message when a search for a certain term results in no matching articles. As any web usability guru will tell you it is very bad practice to leave users staring at a blank page. They will instantly shy away assuming your website is somehow broken.

To overcome this limitation one could hunt for a suitable Textpattern plugin, or jot down a small sequence of PHP code into the page template.

I’ve chosen to go the DIY route.

Some technical details of Textpattern full text search

In Textpattern 4.0.3, the number of resulting matches is held in $thispage['total'], a global variable which will receive a valid value after the article list is rendered. Please note that more recent revisions of Textpattern keep this count in $thispage['grand_total'] due to a bug fix which was applied after the shipment of Textpattern 4.0.3. The search term can be found in $q, respectively.

Knitting it all together

So by pulling those two global values into a short snippet of PHP the search result list is adornable by a message which clearly indicates success or failure to the user:

global $thispage;
global $q;
$q1 = htmlentities($q);
echo( ($thispage['total']==0 ?
"Sorry, no match found for your request." :
"Your search for <strong>$q1.</strong> resulted in "
.$thispage['total']." hits.") );

This sequence will either print “Sorry, no match found for your request.” or “Your search for searchterm resulted in number hits.”.

Too verbose? Use this stripped down version which offers to continue the search on Google (limited to results from your site, of course):

global $thispage;
global $q;
$q1 = htmlentities($q);
if ($thispage['total']==0) {
  echo("<p>Sorry, no match found for your request.</p>");
  <a href=\"$q".
  "+site%3A".hu."\">Google</a> for $q1</p>.");

Put one of those two alternatives into a page template of your choosing, properly embraced by a conditional <txp:if_search> tag pair. That’s about all. Fine user experiences guaranteed.


  1. Thanks for this tutorial! It was very helpful!