redirect-to-single-post

How to redirect to single post page if there is one post in category/tag

on February 15, 2011 | 1,301 views

Archive indexes are a good way to organize your posts, but if there is only one post in an archive page it can be just a waste of time. Here i will give you a small #snippet to jump directly to the post page.

To achieve this we will use wp_redirect which is a great feature for contexual template redirections.

Here is the code to put in your functions.php file to jump single post archives :

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');

This redirection check will fast forward user to the post page if there is only one post in that category/tag.

Thanks to Julie for the idea.

About Shailan.com Staff

Shailan.com is a design blog about WordPress and web design. We regularly write about wordpress, plugins, themes, web design resources, php, css, jquery, adsense and more.. If you want to get notified about our posts, be sure to subscribe to our feed or follow us on facebook.

Share Your Thoughts

Your email address will not be published.


16 thoughts on “How to redirect to single post page if there is one post in category/tag”

  1. Pingback: Anusvaar
  2. Fanatastic! Thanks a lot! I was looking for this.

    Do you know if this is creates 301 redirects?

  3. Jan says:

    I don’t see the date of this article, am I blind? Can I just drop here a line to mention, that such time sensitive subjects need to give a reader some idea, when was it written. But anyway, thanks for sharing, this is exactly my case.