# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Redirects](https://wpide.com/library/category/redirects/)
- Tags: redirects, pagination, 404
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/redirect-page-numbers-past-the-end/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Send Page Numbers Past the End to the Last Page" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
