I have a site that has changed its pagination structure, resulting in a huge amount of 404 errors (more posts are being shown per page than previously, so there are lots of pages that were once indexed in search engines that are now 404'ing).
What I want to do is create a function that will check whether a page number is greater than the max_num_pages value, and if that's the case interrupt the default wordpress behaviour which is to serve a 404 page, and instead 301 redirect it to either the home page, or better still the initial tag page chosen (we're only interested in tag pages in the overall structure).
What I don't know though is how - or more precisely when to use this function. I'm guessing that WordPress already has a function that checks this info, which in turn triggers the 404, so maybe I need to set it up as a filter to an existing pluggable function?
The function so far is
redirect_tags(){
if (is_main_query() && !is_singular() && is_paged())
{global $wp_query;
$paged = intval(get_query_var('paged'));
$max_page = $wp_query->max_num_pages;
if($max_page < $paged){
echo 'page is greater than max';}
}}