Did you know that activating WordPress permalinks also activates the /search/ URL prefix?
Note: When you switch on permalinks, not only do you get the pretty URLs, but links with the post ID get redirected to their pretty URL. For example: http://www.tcbarrett.com/?p=604
Working on a directory type site for a client, I wanted to be able to link deeply into the site’s content. With thousands of possible search results, it becomes important for visitors to be able to refine their search choice. As well as the individual profiles, we want people to find lists of profiles too (e.g. subsets of categories, depending on search term).
I started building a /search/ rewrite (to map onto the ‘s‘ query variable), only to discover that WordPress already has it! It think that because ‘?s=‘ is not redirect as it is for posts and pages, I assumed that it didn’t exist.
Pretty search URL in action: http://www.tcbarrett.com/?s=pretty search
My First Attempt – Oops
Having found out about the inbuilt search variable, I did a quick and dirty nginx rewrite for my development
if ( $arg_s ) {
rewrite ^ $scheme://$host/search/$arg_s/ redirect;
}
However, I found that a whole bunch of things broke in admin. All the back-end admin searches also use the ‘s‘ query var. Even on my development box, I couldn’t cope with that for long.
The second attempt – rookie
Realising that the redirect needs to be handled by WordPress, and front end only, I knocked up a snippet for the theme functions.php file:
add_action( 'template_redirect', 'tcb_search_pretty_permalinks' );
function tcb_search_pretty_permalinks(){
if( !is_admin() and is_search() ):
if( $search = $_GET['s'] ):
wp_redirect( home_url("search/{$search}/") );
exit;
endif;
endif;
}
And lo, there is a plugin for that.
I thought a little strange that this wasn’t all in core, so I asked about on the WordPress mailing list. I was directed to a plugin. This is WordPress, so of course there is a plugin! And it does it better.
I’m still a little confused why it can’t be in core. But hey-ho.