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.

Photo: Direction sign from BigStock