Filter and Search WordPress Posts Without a Page Reload, in Plain JavaScript

The articles page on this site has category filters, a search box and a Load more button. None of them reload the page. There’s no React behind it, no REST API call and no JSON. It’s about a hundred lines of plain JavaScript, and it works by asking WordPress for pages it already knows how to make.

The Idea

Every filter on that page is a real link. “WordPress” points at /category/wordpress/, which is an ordinary category archive. Page two is /category/wordpress/page/2/. WordPress renders all of those on the server with the same template.

So the script doesn’t build anything. When you click a filter it fetches that archive as HTML, pulls the list of posts out of the response, and drops it into the page you’re on. If JavaScript fails, the links still go where they say. A search engine sees normal archives.

The usual way to do this is to call the REST API and build the markup in JavaScript. That means writing the row template twice, once in PHP and once in JS, and keeping the two in step forever. Fetching the HTML means there’s only ever one template.

Fetching a Page and Taking the Rows

DOMParser turns the response into a document you can query like any other. It never touches the page, and scripts inside it don’t run.

JavaScript
const list = document.querySelector('.articles .wp-block-post-template');

let base = location.pathname.replace(/page\/\d+\/?$/, '').replace(/\/$/, '');
let term = '';

const urlFor = (page) =>
    base + (page > 1 ? '/page/' + page + '/' : '/') +
    (term ? '?ab_q=' + encodeURIComponent(term) : '');

const fetchPage = async (page, signal) => {
    const res = await fetch(urlFor(page), { signal });
    if (!res.ok) return [];
    const doc = new DOMParser().parseFromString(await res.text(), 'text/html');
    return [...doc.querySelectorAll('.articles .wp-block-post-template > li')];
};

base is the archive being shown and term is the search phrase. Between them they describe everything on screen, so every request is built from those two values.

Swapping the List

JavaScript
let ctl = null;

const refresh = async () => {
    if (ctl) ctl.abort();
    ctl = new AbortController();
    const mine = ctl;
    list.classList.add('is-loading');
    try {
        const items = await fetchPage(1, mine.signal);
        list.replaceChildren(...items.map((li) => document.adoptNode(li)));
    } catch (err) {
        // replaced by a newer request, or offline
    } finally {
        if (ctl === mine) list.classList.remove('is-loading');
    }
};

The AbortController is the part people skip. Without it, someone who clicks two filters quickly can get the first answer after the second, and end up looking at the wrong list under the right heading. Aborting the old request whenever a new one starts makes that impossible.

adoptNode moves each row from the parsed document into the live one. replaceChildren swaps the whole list in a single step, so there’s no moment where it’s empty.

The Filters

One listener on the filter list handles every link in it.

JavaScript
filters.addEventListener('click', (e) => {
    const a = e.target.closest('a');
    if (!a || e.metaKey || e.ctrlKey || e.shiftKey || e.button) return;
    e.preventDefault();
    base = new URL(a.href).pathname.replace(/\/$/, '');
    history.replaceState(history.state, '', base + '/');
    refresh();
});

The check for modifier keys is there so Cmd-click still opens the category in a new tab. Hijacking a link is fine. Breaking what people expect a link to do isn’t.

replaceState puts the category URL in the address bar, so the page can be copied, shared or reloaded and still show the same thing.

Search

WordPress search normally sends you to the search template, which looks nothing like the article list. I wanted results in the same list, inside whichever category was selected. So the script adds its own query parameter and a few lines of PHP turn it into a search within the current archive.

PHP
add_action( 'pre_get_posts', function ( $query ) {
    if ( is_admin() || ! $query->is_main_query() || ! isset( $_GET['ab_q'] ) ) {
        return;
    }
    if ( $query->is_home() || $query->is_category() ) {
        $query->set( 's', sanitize_text_field( wp_unslash( $_GET['ab_q'] ) ) );
    }
} );

On the JavaScript side the only trick is waiting until the typing stops.

JavaScript
let timer = 0;

input.addEventListener('input', () => {
    clearTimeout(timer);
    const q = input.value.trim();
    const next = q.length < 2 ? '' : q;
    if (next === term) return;
    timer = setTimeout(() => {
        term = next;
        refresh();
    }, 250);
});

A quarter of a second is long enough that a fast typist sends one request for a word and short enough that it still feels live. Anything under two characters is treated as no search, because a one-letter search matches nearly every post.

Load More

Load more is the same fetch with a page number, appended instead of swapped.

JavaScript
const PER_PAGE = 9;
let nextPage = 2;

button.addEventListener('click', async () => {
    button.disabled = true;
    const items = await fetchPage(nextPage);
    items.forEach((li) => list.appendChild(document.adoptNode(li)));
    nextPage++;
    button.hidden = items.length < PER_PAGE;
    button.disabled = false;
});

There's no need to ask WordPress how many pages exist. A page that comes back with fewer than nine posts was the last one, so the button hides itself.

What It Costs

Each request downloads a whole HTML page to use one list from it, which is more bytes than a JSON response would be. On this site the archive pages are small and they come from the page cache, so I've never been able to make it feel slow.

If your archive pages are heavy, or the list needs to do something the server can't render, the REST API is the right tool. For a blog index it's more machinery than the job needs.

Filed under: ,
Share

Leave a Reply

Your email address will not be published. Required fields are marked *