redirect pages with no content, instead of 404 error, using max_num_posts?

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';}
 }}

1 Answer
1

If the rest of your function works you just need to add a call to wp_safe_redirect and hook the whole thing into WordPress. I think that the first hook that will have a populated $wp_query is wp. So alter the last part of your function…

if($max_page < $paged){
    wp_safe_redirect(get_bloginof('url'),'301');
}

And then add the following after (outside) the function.

add_action('wp','redirect_tags');

I think that should do it. You can setup infinite redirect loops so be careful.

Edit: The problem is the is_paged() check at the top of your function. If you try to access a pagination page that doesn’t exist is_paged() returns false and none of the rest of your function runs. Remove that check, and hook to template_redirect. I tested this and it does work. In other words…

function redirect_tags() {
  if (is_main_query() && !is_singular() ) {
    global $wp_query;
    $paged = intval(get_query_var('paged'));
    $max_page = $wp_query->max_num_pages;
    if ( ($max_page < $paged) ) {
      wp_safe_redirect(get_bloginfo('url'),'301');
    }
  }
}
add_filter('template_redirect','redirect_tags');

Leave a Comment