Infinite Scroll is a popular way to dynamically load fresh content into a site as a user scrolls down through it. It’s also quite easy to code into a WordPress theme. Here’s a quick walkthrough of how to do it:
(If you’re looking for a plugin to do this instead, use the “Infinite Scroll” module in the Jetpack plugin).
Get the Script Assets
Pick out the ajax-loader.gif of your choice, and add it to your theme “images” folder.
Enqueue the Script
You’ll need to register and enqueue the required script in functions.php:
[gist id=”399e8c6966360dbac708ffff4178b780″ file=”enqueue.php” lines=”2-18″]
Init the Script
In the code snippet below I list the parameters I used in my theme. You’ll likely need to customize these in order to match your theme markup:
- img: The path to the ajax loader image
- nextSelector: Selector for the “previous posts” link.
- navSelector: Containing selector for the previous/next navigation links.
- itemSelector: Selector for posts. This might be .hentry, .post, .etc
- contentSelector: Containing div for your posts.
[gist id=”399e8c6966360dbac708ffff4178b780″ file=”enqueue.php” lines=”20-42″]
Note: Also make sure to update “custom” to your own textdomain for translations.
Try it out
I wrote a little more about some of those issues in this post