Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.