Send Page Numbers Past the End to the Last Page
When someone opens a page number that no longer exists, such as /category/news/page/40/ after you deleted posts, sends them to the real last page instead of a 404.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
global $wp_query;
$paged = (int) get_query_var( 'paged' );
// A list page (blog, archive, search) asked for a page number that does not exist.
if ( ! is_404() || $paged < 2 ) {
return;
}
$vars = $wp_query->query_vars;
$vars['paged'] = 1;
$vars['fields'] = 'ids';
$vars['no_found_rows'] = false;
$vars['posts_per_page'] = max( 1, (int) $wp_query->get( 'posts_per_page' ) );
$check = new WP_Query( $vars );
$last = (int) $check->max_num_pages;
if ( $last < 1 || $paged <= $last ) {
return;
}
// /category/news/page/40/ goes to the real last page, for example /category/news/page/7/.
wp_safe_redirect( get_pagenum_link( $last, false ), 301 );
exit;
} );
Notes
Works for the blog page, archives and search results.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.