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

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

There’s a piece of code that I found interesting. 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.

FREE EBOOK
Your step-by-step roadmap to a profitable web dev business. From landing more clients to scaling like crazy.

By downloading this ebook I consent to occasionally receive emails from WPMU DEV.
We keep your email 100% private and do not spam.

FREE EBOOK
Plan, build, and launch your next WP site without a hitch. Our checklist makes the process easy and repeatable.

By downloading this ebook I consent to occasionally receive emails from WPMU DEV.
We keep your email 100% private and do not spam.

Tags: