WordPress search and pretty URLs (deep linking into your site’s content)

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.

http://wordpress.org/extend/plugins/nice-search

WordPress search – redirect on single result

The days of ‘everything should be at most 3 clicks away‘ have gone. Even so, if you want to save your visitors a click, you can automatically redirect them to their result when the WordPress search returns a single hit.

function tcb_redirect_to_single_search_result() {
  if( is_search() ){
    global $wp_query;
    if( $wp_query->post_count == 1 ){
      wp_redirect( get_permalink($wp_query->posts['0']->ID), 302 );
      exit;
    }
  }
}
add_action('template_redirect', 'tcb_redirect_to_single_search_result');

The wp_redirect() 302 argument is the default value, but I like to explicitly set it. As popular as 301 redirects are, they really do not suit this scenario.