Redirect WordPress Visitors to Full Post if Only One Post in Category


This is nifty little piece of code I found on Shailan.com. If there is only one post in a category, then when someone clicks on the category link, it will take them directly to the full post instead of taking them to the category page (where there will only be one result). In short, it eliminates the unnecessary extra step that the default WordPress set up would take you through.

This also works for tags.

To add the code below to your functions.php file, go to Appearance > Editor > Theme Functions – functions.php.

function stf_redirect_to_post(){
 global $wp_query;
 // If there is one post on archive page
 if( is_archive() && $wp_query->post_count == 1 ){
 // Setup post data
 the_post();
 // Get permalink
 $post_url = get_permalink();
 // Redirect to post page
 wp_redirect( $post_url );
 }
 } add_action('template_redirect', 'stf_redirect_to_post');

If you would like to turn this snippet of code into your own personal plugin, then this post can teach you how.

Featured Plugin - WordPress Infinite SEO Plugin

Fully integrated with the SEOMoz API, complete with automatic links, sitemaps and SEO optimization of your WordPress setup - this is the only plugin you need to help you rank your site number 1 on Google - nothing else compares.
Find out more

Photo: Direction sign from BigStock

Tags

Comments (3)

  1. Thank you! Works fine on one of my blog. But on my other blog writes “Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.” What’s the problem?

  2. This is exactly what I have been searching for, but as I am not a programmer (and relatively new to WordPress…been building all of my sites/client sites in Dreamweaver), where in the functions.php code do I insert the code you provided? Here is the full contents of my functions.php file. Any help would be greatly appreciated. Thank you!

  3. Hi – You just need to put it inside your php tags, so you can put it right before the ?> tag at the end of your file.

    As mentioned in the post, you can also make this into a plugin. That way if you change themes, you won’t have to redo it.

Participate