Web Programming

Nice searching in WordPress

<![CDATA[You may have noticed that all the tags on my posts point to URLs of the form /ob-search/search+term. That’s a reasonably simple bit of mod rewriting. This article is aimed at people who can do that.

I wanted a way for the search box to point to the same pages. I figured I could point the search form at a fake page and redirect (it with a HTTP status code of 302 so it is sent to the browser and the user sees it in his/her address bar) to the nice URL (which would secretly redirect to the real one).

So I came up with the following:

RewriteRule ^fake-search.php?s=(*.)$ /ob-search/$1

It didn’t work. Unfortunately Apache strips of query strings before the get to Rewriting and the reattaches them. So to sort it out I had to hack off the query string with one rule (which is accessed using an environment variable) and then extract the bit I wanted with another rule:

RewriteRule fake-search.php /-%{QUERY_STRING}?
RewriteRule ^/-s=(.*)$ /ob-search/$1 [R=302]
RewriteRule ^/ob-search/(.*)$ /index.php?s=$1

The third rule just does the “simple” redirecting as a said in the beginning.

The ? appending the query string on to the end afterwards. The hyphen in the first two lines could be anything you want – it’s just something for the second rule to recognise.

To finish it off I altered the search form’s action attribute to point to fake-search.php and all was well 🙂 Try it 😀

PHP, WordPress, Apache, mod_rewrite, mod rewrite]]>


One thought on “Nice searching in WordPress

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s