Implementing a sitewide search function

Those of you coming to this site more often might have noticed a small change in the search box. It’s now implemented sitewide, and I’ve built a sitewide search functions using the Yahoo! API. It was quite nescessary because I found that people were searching for “” on the blog, and they wouldn’t find anything since the pages for the sortable table script are static.

Keeping track of what people are searching for
I had a few things to make sure while building this search function. First of all, I wanted to have the same info I get when I look at the statistics page for the Search Meter WordPress plugin. Secondly, I wanted to show more then just the post or page title. The last, but also very important demand I have is that it’s fast. Well the first one was quite easy, I decided to put the data into the table for the search meter plugin and just use that interface, instead of writing that myself. The function was basically adapted from the code of the plugin:

[code lang="php"]
function save_search($searchstring, $numresults) {
global $table_prefix;
// Save into the DB. Usually this will be a new query, so try to insert first
$query = "INSERT INTO {$table_prefix}searchmeter (terms,date,count,last_hits) VALUES ('$searchstring',CURDATE(),1,$numresults)";
$success = mysql_query($query);
if (!$success) {
$query = "UPDATE '{$table_prefix}searchmeter' SET count = count + 1, last_hits = $numresults WHERE terms = '$searchstring' AND date = CURDATE()";
$success = mysql_query($query);
return true;

Constructing the Yahoo! API query
The second thing wasn’t too hard to do either, as Yahoo! returns a snippet with the searchresult for the query. The REST query is constructed as follows:

[code lang="php"]
$query = "".urlencode($searchstring);
$request = ''.$yahooappid.'&query='.$query.'&output=php';

The part output=php makes the API return serialized PHP, which, after calling unserialize, turns into a nice clean array, which you can then loop through to display the results.

The only thing left was adding the search box to my layout for the non-blog pages, and fixing the blog to look the same. In the theme I had to change the action URL of the searchform.php file to /search/, and there it was: my new site wide search function!

So far, it’s all good. I’ve got a few things left, like building in paging so you can see more than 10 results. I’ve got one thing that bothers me though: it’s a bit slow. Of course I could solve this by spidering my own site with something like ht://Dig, but I think there ought to be a better solution… Perhaps you guys and girls know of one?

Coming up next!

1 Response to Implementing a sitewide search function