Halloween Sale 15% off Ends in See the plans
PHP

Prefetch the Next Page of Archives and Paginated Posts

Adds a prefetch hint for the next page of blog archives, category pages and multi-page posts, so it opens almost instantly when visitors click "Next".

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

Code

add_action( 'wp_head', function () {
    global $wp_query, $page, $numpages;

    $next = '';

    if ( ( is_home() || is_archive() || is_search() ) && get_query_var( 'paged', 1 ) < (int) $wp_query->max_num_pages ) {
        $next = get_next_posts_page_link();
    } elseif ( is_singular() && $numpages > 1 && $page < $numpages ) {
        $next = _wp_link_page( $page + 1 );
        $next = preg_match( '#href="([^"]+)"#', $next, $m ) ? $m[1] : '';
    }

    if ( $next ) {
        printf( "<script>if(!(navigator.connection&&navigator.connection.saveData)){var l=document.createElement('link');l.rel='prefetch';l.href=%s;document.head.appendChild(l);}</script>\n", wp_json_encode( esc_url_raw( $next ) ) );
    }
}, 20 );

Notes

Prefetching uses a little extra bandwidth for visitors who never click; it is skipped for visitors with data saver turned on.

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.