Build an Infinite Scroll Post Feed with the Fetch API and WordPress REST API

Infinite scroll with the Fetch API and the WordPress REST API

Infinite scroll loads the next page of posts when the visitor reaches the end of the list. With an Intersection Observer watching a marker below the list and the REST API delivering the posts as JSON, it needs no plugin and no jQuery. Done carefully, it keeps a real “Next page” link for search engines and for visitors without JavaScript.

Problem: The blog archive shows ten posts and a pagination, and the theme should load the following posts automatically as the visitor scrolls, without breaking pagination for crawlers.

Solution: Keep the normal pagination in the markup, observe an empty element after the list with IntersectionObserver, fetch the next page from /wp/v2/posts with _embed and _fields, read the total from the X-WP-TotalPages header, render the cards with escaped text, and announce new posts in an aria-live region.

The markup

<div class="ha-posts" data-per-page="10" data-category="0">
    <!-- the first ten cards, rendered by PHP -->
</div>
<div class="ha-posts__end" aria-hidden="true"></div>
<p class="screen-reader-text" aria-live="polite"></p>
<nav class="pagination"><!-- the_posts_pagination() --></nav>

Pass the API URL

add_action( 'wp_enqueue_scripts', function () {
    if ( ! ( is_home() || is_category() ) ) {
        return;
    }
    wp_enqueue_script( 'ha-infinite', get_theme_file_uri( 'js/infinite.js' ), [], '1.0.0', true );
    wp_add_inline_script( 'ha-infinite', 'window.haInfinite = ' . wp_json_encode( [
        'api'      => rest_url( 'wp/v2/posts' ),
        'category' => is_category() ? get_queried_object_id() : 0,
    ] ) . ';', 'before' );
} );

The script

( function () {
    const list = document.querySelector( '.ha-posts' );
    const end = document.querySelector( '.ha-posts__end' );
    const live = document.querySelector( '[aria-live="polite"]' );
    if ( ! list || ! end || ! window.haInfinite || ! ( 'IntersectionObserver' in window ) ) {
        return;
    }

    let page = 1;
    let totalPages = Infinity;
    let loading = false;

    const escape = ( text ) => {
        const div = document.createElement( 'div' );
        div.textContent = text;
        return div.innerHTML;
    };

    async function loadNext() {
        if ( loading || page >= totalPages ) {
            return;
        }
        loading = true;
        const url = new URL( window.haInfinite.api );
        url.searchParams.set( 'page', page + 1 );
        url.searchParams.set( 'per_page', list.dataset.perPage );
        url.searchParams.set( '_fields', 'link,title,excerpt' );
        if ( window.haInfinite.category ) {
            url.searchParams.set( 'categories', window.haInfinite.category );
        }

        try {
            const response = await fetch( url );
            if ( ! response.ok ) {
                throw new Error( response.status );
            }
            totalPages = Number( response.headers.get( 'X-WP-TotalPages' ) ) || page + 1;
            const posts = await response.json();
            list.insertAdjacentHTML( 'beforeend', posts.map( ( post ) => `
                <article class="ha-card">
                    <h2><a href="${ encodeURI( post.link ) }">${ escape( post.title.rendered.replace( /<[^>]+>/g, '' ) ) }</a></h2>
                    <div class="ha-card__excerpt">${ post.excerpt.rendered }</div>
                </article>` ).join( '' ) );
            page++;
            live.textContent = `${ posts.length } more posts loaded`;
            if ( page >= totalPages ) {
                observer.disconnect();
            }
        } catch ( error ) {
            observer.disconnect(); // the normal pagination stays as fallback
        } finally {
            loading = false;
        }
    }

    const observer = new IntersectionObserver( ( entries ) => {
        if ( entries[ 0 ].isIntersecting ) {
            loadNext();
        }
    }, { rootMargin: '400px' } );

    observer.observe( end );
    document.querySelector( '.pagination' )?.setAttribute( 'hidden', '' );
} )();

rootMargin: '400px' starts loading before the visitor actually reaches the end, so the posts are usually there in time. _fields keeps the response small. The excerpt is HTML that WordPress already filtered for output, the title is converted to plain text and escaped. If a request fails, the observer stops; the pagination is hidden only by the script, so it is still in the HTML for crawlers.

The basics of calling the REST API with fetch(): the Fetch API and the WordPress REST API.

NOTE: Infinite scroll makes the footer unreachable on long archives and loses the scroll position when the visitor opens a post and comes back. For many blogs a “Load more” button, with the same loadNext() on click, is the better choice. Update the address with history.replaceState() to /page/N/ after each load if visitors should be able to share or return to the position.