← All posts

WordPress: add a “Load more posts” button without reloading the page (REST API and fetch)

A "Load more" button on a WordPress archive page, done properly: a REST route that returns the card HTML, accessible JavaScript, and the duplicate-post, caching and SEO pitfalls.

WordPress: add a "Load more posts" button without reloading the page (REST API and fetch)

Key points

  • A dedicated REST route that returns card HTML rendered by the page’s own template saves you from duplicating markup in JavaScript.
  • Keep the regular pagination in the page: search engines use it, and it’s your fallback if JavaScript fails.
  • Duplicates come from sticky posts and from posts published between two clicks; freezing a reference date prevents them.

A “Load more posts” button is one of the features we’re asked for most on blogs and news sites. Numbered pagination feels dated on mobile, and infinite scroll brings its own problems: an unreachable footer, and a back button that loses your place. Here’s the version we use on our projects: a REST route that reuses the existing PHP template, an accessible script, and fixes for the three problems that reliably show up once the feature is live.

Why a REST route rather than admin-ajax

admin-ajax.php works, but it boots a large part of the admin on every call and doesn’t lend itself to simple HTTP caching, since everything is a POST to the same URL. A GET REST route gives each page of results its own clean URL, which the browser, a CDN or a page cache can hold onto for a few minutes.

Then there’s the question of what the route returns. The standard /wp/v2/posts endpoint returns raw data: title, excerpt, featured image ID. You then have to rebuild the post card in JavaScript, deal with image sizes, categories, formatted dates, and remember to update both versions every time the design changes. We prefer a custom route that returns the HTML directly, generated by the same get_template_part() call the page uses. One source of truth for the markup, and loaded cards that are pixel-identical to the ones on the first page.

The template: list, button and fallback pagination

In your archive template (index.php, archive.php or home.php depending on the theme), the loop stays the same. After it, add a button carrying what the script needs in data- attributes, a live region for screen readers, and the usual pagination:

<div id="post-list" class="post-grid">
	<?php while ( have_posts() ) : the_post(); ?>
		<?php get_template_part( 'template-parts/post-card' ); ?>
	<?php endwhile; ?>
</div>

<?php global $wp_query; if ( $wp_query->max_num_pages > 1 ) : ?>
	<button type="button" id="load-more" class="button" hidden
		data-api="<?php echo esc_url( rest_url( 'site/v1/posts' ) ); ?>"
		data-page="1"
		data-category="<?php echo is_category() ? (int) get_queried_object_id() : 0; ?>"
		data-before="<?php echo esc_attr( gmdate( 'Y-m-d H:i:s' ) ); ?>">
		Show more posts
	</button>
	<p id="load-more-status" class="screen-reader-text" aria-live="polite"></p>
	<nav class="classic-pagination"><?php the_posts_pagination(); ?></nav>
<?php endif; ?>

Three details matter. The button is hidden by default (hidden) and JavaScript reveals it, so a visitor without the script sees normal pagination and never faces a button that does nothing. The pagination stays in the HTML so search engines can follow the links to pages 2, 3 and beyond: crawlers don’t click JavaScript buttons. And data-before records the moment the page was rendered, which we’ll use to prevent duplicates.

The REST route that returns card HTML

In your site plugin or the theme’s functions.php, register the route and its callback:

add_action( 'rest_api_init', function () {
	register_rest_route( 'site/v1', '/posts', [
		'methods'             => 'GET',
		'callback'            => 'site_rest_posts',
		'permission_callback' => '__return_true', // public content only
		'args'                => [
			'page'      => [ 'type' => 'integer', 'minimum' => 2, 'required' => true ],
			'category' => [ 'type' => 'integer', 'minimum' => 0, 'default' => 0 ],
			'before_date'     => [ 'type' => 'string', 'format' => 'date-time', 'required' => true ],
		],
	] );
} );

function site_rest_posts( WP_REST_Request $req ) {
	$args = [
		'post_type'           => 'post',
		'post_status'         => 'publish',
		'paged'               => $req['page'],
		'posts_per_page'      => (int) get_option( 'posts_per_page' ),
		'ignore_sticky_posts' => true,
		'post__not_in'        => get_option( 'sticky_posts' ),
		'date_query'          => [ [ 'column' => 'post_date_gmt', 'before' => $req['before_date'], 'inclusive' => true ] ],
	];
	if ( $req['category'] ) {
		$args['cat'] = $req['category'];
	}
	$q = new WP_Query( $args );

	ob_start();
	while ( $q->have_posts() ) {
		$q->the_post();
		get_template_part( 'template-parts/post-card' );
	}
	wp_reset_postdata();

	$res = new WP_REST_Response( [
		'html' => ob_get_clean(),
		'max'  => (int) $q->max_num_pages,
	] );
	$res->header( 'Cache-Control', 'public, max-age=300' );
	return $res;
}

Parameters are declared with types and bounds, so WordPress validates the request before your callback runs, and a page 0 or a non-numeric category is rejected with a clean 400 error. The permission_callback is explicit: since WordPress 5.5, leaving it out triggers a notice, and writing it forces you to think about access. Here the answer is “everyone”, because the query only returns published posts.

Rendering goes through ob_start() and ob_get_clean(): the card template echoes its output, and we simply capture it. Don’t forget wp_reset_postdata() after the loop, or functions called afterwards may operate on the last post in the list. The Cache-Control header allows five minutes of caching; tune it to how often you publish, and check that your caching plugin or CDN isn’t holding API responses forever.

The JavaScript: fetch, button state and accessibility

The script is about forty lines, no jQuery, no library:

const button = document.getElementById('load-more');

if (button) {
  const list = document.getElementById('post-list');
  const status = document.getElementById('load-more-status');
  const pagination = document.querySelector('.classic-pagination');

  // JavaScript works: swap the pagination for the button
  button.hidden = false;
  if (pagination) pagination.hidden = true;

  button.addEventListener('click', async () => {
    const page = Number(button.dataset.page) + 1;
    const url = new URL(button.dataset.api);
    url.searchParams.set('page', page);
    url.searchParams.set('category', button.dataset.category);
    url.searchParams.set('before_date', button.dataset.before.replace(' ', 'T'));

    button.disabled = true;
    button.setAttribute('aria-busy', 'true');
    status.textContent = 'Loading…';

    try {
      const res = await fetch(url, { headers: { Accept: 'application/json' } });
      if (!res.ok) throw new Error('HTTP ' + res.status);
      const data = await res.json();

      const first = list.children.length;
      list.insertAdjacentHTML('beforeend', data.html);
      button.dataset.page = page;
      status.textContent = 'More posts loaded.';

      // Move focus to the first new post (keyboard and screen reader users)
      list.children[first]?.querySelector('a')?.focus();

      if (page >= data.max) button.remove();
    } catch (err) {
      status.textContent = 'Loading failed.';
      button.remove();
      if (pagination) pagination.hidden = false; // fallback: regular links
    } finally {
      button.disabled = false;
      button.removeAttribute('aria-busy');
    }
  });
}

The button is disabled while the request runs, which stops a double click from loading the same page twice. aria-busy and the aria-live region tell screen reader users what’s happening; without them, a blind user clicks and gets no feedback at all. Moving focus to the first new post is the step most implementations skip: without it, keyboard users stay on the button (or land at the top of the page if it disappeared) and have to tab through everything again.

On error, the script removes the button and brings back the regular pagination, so the visitor always has a way to reach older posts.

Three problems you’ll meet in production

Duplicate posts. It has two causes. First, sticky posts, which WordPress pins to the top of page 1 on the blog home, show up again further down when you load more. Excluding sticky_posts in the route fixes it; if you don’t use sticky posts on the home page, adjust accordingly. Second, a post published between page load and the click shifts the whole pagination by one, so the last post of page 1 reappears at the top of page 2. The before_date parameter, passed to date_query, freezes the list as it was when the page loaded.

Losing your place on back navigation. A visitor loads three extra batches, opens a post, then hits Back, and the list is back to page 1. If that matters for your site, record the page reached in the URL with history.replaceState() and use it on load.

SEO. As long as the regular pagination stays in the HTML, nothing changes for search engines: they follow the /page/2/ links, which still work. Trouble starts when someone removes those links because they seem unused, leaving older posts reachable only through the sitemap.

FAQ

Is a “Load more” button better than infinite scroll?

On most content sites, yes: visitors stay in control, the footer remains reachable, and it’s simpler to make accessible. Infinite scroll suits feeds where people browse without looking for anything in particular.

Does the button work with a page caching plugin?

Yes. The page itself is cached as usual, and the REST route is a separate URL. Just make sure API responses aren’t cached for too long, or new posts will take a while to show up in loaded batches.

Want better navigation on your WordPress blog or news site? We build custom themes and features that are fast, accessible and designed with SEO in mind.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →