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:
add_action('template_redirect', 'archive_to_blog');
function archive_to_blog () {
global $wp;
$page_url = $wp->request;
$first_level_url = explode('/', $page_url);
// Check and exclude url that does not contain tag or category
if ( $first_level_url[0] !== 'tag' && $first_level_url[0] !== 'category' ) {
return;
}
if ( is_404() ) {
// Finally, just 301 redirect them into whatever link you want.
wp_redirect('/blog/', 301);
exit;
}
}
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().
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.