"Load More" Button for Blog Archives
Replaces the numbered pagination on blog and category pages with a "Load more posts" button that adds the next page of posts without leaving the page.
Opens WPIDE on
Code
<script>
(function () {
var containerSel = '.wp-block-post-template, #main, .site-main';
var itemSel = '.wp-block-post-template > li, article.post, article.type-post';
var nextSel = '.wp-block-query-pagination-next, .nav-links a.next, a.next.page-numbers';
var pagerSel = '.wp-block-query-pagination, .navigation.pagination, .nav-links';
var next = document.querySelector(nextSel);
var container = document.querySelector(containerSel);
if (!next || !container || !window.fetch || !window.DOMParser) { return; }
var pager = next.closest(pagerSel) || next.parentNode;
var button = document.createElement('button');
button.type = 'button';
button.className = 'wp-element-button wpide-load-more';
button.textContent = 'Load more posts';
button.style.cssText = 'display:block;margin:2em auto;';
var status = document.createElement('p');
status.className = 'screen-reader-text';
status.setAttribute('aria-live', 'polite');
pager.parentNode.insertBefore(button, pager);
pager.parentNode.insertBefore(status, pager);
pager.style.display = 'none';
var url = next.href;
button.addEventListener('click', function () {
button.disabled = true;
button.textContent = 'Loading…';
fetch(url, { credentials: 'same-origin' }).then(function (r) { return r.text(); }).then(function (html) {
var doc = new DOMParser().parseFromString(html, 'text/html');
var items = doc.querySelectorAll(itemSel);
var current = container.querySelectorAll(itemSel);
var anchor = current[current.length - 1];
items.forEach(function (item) {
var node = document.importNode(item, true);
if (anchor) { anchor.parentNode.insertBefore(node, anchor.nextSibling); anchor = node; } else { container.appendChild(node); }
});
status.textContent = items.length + ' more posts loaded';
var more = doc.querySelector(nextSel);
if (more && more.href) {
url = more.href;
button.disabled = false;
button.textContent = 'Load more posts';
} else {
button.remove();
}
}).catch(function () {
window.location.href = url;
});
});
})();
</script>
Notes
Set the container and post selectors at the top of the script to match your theme (defaults cover most classic and block themes). Without JavaScript the normal pagination stays.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.