If you restructure tags and categories of your WordPress website, for example renaming, removing, or deleting, you would have a lot of broken links made by the change. This post shows you how to make a redirect that all 404 archive pages will be forwarded to the blog post page, or a new page that you define.
Here is the code that you can place into the file functions.php of the theme:
It is quite clear what it will do. First, before WordPress checks which template to load (with template_redirect hook), the function archive_to_blog will request the url from the browser address bar.
If it is an archive page, the expected result would be: tag/tagname or category/categoryname.
Then, we extract the returned url with explode. After that, we check if the first part of the url is are tag or category. If not, returns at once. If they are, then continue checking are they broken links with WordPress built-in function is_404().
Finally, just 301 redirect them into whatever link you want.
The downside of this solution is that it checks every links return, to find if the page is a 404 tag or category page. It is somehow unnecessary in my opinion.
- template_redirect hook
- Print out page template with get_page_template()
Leave a Reply