[WordPress] Redirect to Single Post if One Post in Archive Page

Updated on     Kisan Patel

Problem:

Redirect to Single Post if One Post in Archive Page

How to redirect user to single post instead of taking user to the category/tag archive page if there is only one post in a category/tag archive page?

Solution

Just add the below code to your functions.php file:

function boot_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', 'boot_redirect_to_post');

Wordpress

Leave a Reply