Be kind and redirect users when there’s only one post in a category found

When you search for something, you have probably got accustomed to getting search results which offer posts and pages containing the search phrase. But if there is only one result found, there’s no need in showing the results – you could redirect user to the post/page directly. We already showed you how to achieve that but what about the category and tag pages?

Similarly, instead of opening a category or tag page which contains only one result, you could redirect that user directly to the post/page. As with the most of our code snippets, it will be enough just to copy and paste the code:

Redirect a user if there was only one post in a category or a tag:

  1. Open functions.php file
  2. Copy and paste the following code:
  3. function redirect_to_post(){
    global $wp_query;
    if( is_archive() && $wp_query->post_count == 1 ){
    the_post();
    $post_url = get_permalink();
    wp_redirect( $post_url );
    }
    } add_action('template_redirect', 'redirect_to_post');
    
  4. Save changes

After you’re done with the code and you have saved the changes, you can test the feature by opening a category or tag page which contains only one post/page in it. Instead of opening a page where only that one post/page is shown, you will be redirected directly to the post. Awesome, isn’t it?

Since some users might get confused by this, it would be a nice idea to include a custom message which will tell users that there was only one result found and that the redirection occurred. If you want to do that, you can leave the message on top of the post/page a user was redirected to by inserting a simple “echo” statement. In that case, you code would look like this:

function redirect_to_post(){
global $wp_query;
if( is_archive() && $wp_query->post_count == 1 ){
the_post();
$post_url = get_permalink();
wp_redirect( $post_url );
}
echo "Since there was only one result found, you have been redirected to this post/page!";
}
add_action('template_redirect', 'redirect_to_post');

Now that even a message has been implemented, you’re done and you won’t have to take care of those categories and tags which contain only one post/page. But don’t let this feature be an excuse for not writing new articles in the category.

Similarly, you can redirect users to a random page or you can do the same for author archive links.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

Your email address will not be published. Required fields are marked *