How To Add A “Load More Posts” Button In WordPress
Today’s featured WordPress tutorial comes from Michael Martin and it’s about replacing the “Older Posts” link on your blog with a button that extends the length of the current web page instead of reloading it; it is similar to how you view older tweets on Twitter.
A partial screenshot of the button
You can check it out on the demo here.
In Michael’s tutorial, you’ll be using AJAX to create the plugin which will have the following features:
- Multiple clicks – First clicks will load page 2?s posts, second will load page 3 etc.)
- Check for posts first – If there are no more posts that can be loaded, we’ll tell the user.
- Degrade gracefully – If a visitor doesn’t use JavaScript, we won’t change the site at all.
Below is a snippet taken from the javascript that makes the AJAX call:
$('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' .post',
function() {
// Update page number and nextLink.
pageNum++;
nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
// Add a new placeholder, for when user clicks again.
$('#pbd-alp-load-posts')
.before('<div ></div>')
// Update the button message.
if(pageNum <= max) {
$('#pbd-alp-load-posts a').text('Load More Posts');
} else {
$('#pbd-alp-load-posts a').text('No more posts to load.');
}
}
);
|
On that note, if you want to see the rest of the code, you can download the completed files as a plugin. All you have to do is upload them in to your WordPress directory and activate it. But if you want to know more about the plugin’s nuts and bolts, you can check out Michael’s tutorial by clicking here.