WordPress: redirect single-result archive pages to the actual post A function.php code snippet to seamlessly redirect category and/or tag pages containing only one post to the post page itself

10 Must-Have features for a WordPress Website in 2019

If you’ve stumbled upon this post it most likely means that you’re running a WordPress blog with a lot of archive pages (categories and/or tags) containing a single post. Archive pages in WordPress are those automatically-generated pages that appear when the user clicks on a category or tag, showing a paged list of all the posts that contain that tag or are related to that category.

These lists are useful when they contain a lot of posts; however, whenever there’s only a single relevant post, it would arguably be better to directly bring the user to the pertaining article, skipping the listing page.

All you have to do to enforce such behaviour is to add the following source code snippet to your WordPress installation’s function.php file:

In order to do that, go to WordPress Administration panel, then navigate through Appearance > Theme Editor: from there, select the function.php file from the list to the right.

It’s worth noting that the above snippet will issue an HTTP 302 redirect, which should be ideal in most scenarios: that said, if you want to issue an HTTP 301 redirect instead, change line 7 accordingly.

That’s about it: I hope that this snippet will be useful for those who want to enforce such behaviour in their WordPress website!

 

About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies. Microsoft MVP for Development Technologies since 2018.

View all posts by Ryan

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.