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
Download a copy of “jquery.infinitescroll.min.js” from the GitHub repository, and drop it into the “scripts” or “js” folder of your WordPress theme.
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:
/**
* Load javascripts used by the theme
*/
function custom_theme_js() {
wp_register_script(
'infinite_scroll',
get_template_directory_uri() . '/js/infinite-scroll.pkgd.min.js',
array('jquery')
null,
true
);
if ( ! is_singular() ) {
wp_enqueue_script( 'infinite_scroll' );
}
}
add_action( 'wp_enqueue_scripts', 'custom_theme_js' );
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.
/**
* Infinite Scroll
*/
function custom_infinite_scroll_js() {
if ( ! is_singular() ) { ?>
<script>
var infinite_scroll = {
loading: {
img: "<?php echo get_template_directory_uri(); ?>/images/ajax-loader.gif",
msgText: "<?php _e( 'Loading the next set of posts...', 'custom' ); ?>",
finishedMsg: "<?php _e( 'All posts loaded.', 'custom' ); ?>"
},
"nextSelector":"#nav-below .nav-previous a",
"navSelector":"#nav-below",
"itemSelector":"article",
"contentSelector":"#content"
};
jQuery( infinite_scroll.contentSelector ).infinitescroll( infinite_scroll );
</script>
<?php
}
}
add_action( 'wp_footer', 'custom_infinite_scroll_js', 100 );
Note: Also make sure to update “custom” to your own textdomain for translations.
Try it out
If you load a category or home page the site should now be infinite scrolling. If not, check the web developer console to see if a script didn’t load or if there’s a javascript error. Also, double check that you’re selectors listed above are all correct.
Possible Issues
If you’re releasing a theme for other people to use, definitely include an option to turn off infinite scroll. It won’t work for everyone- especially if they have plugins that add social buttons or render additional javascript in the post content.
I wrote a little more about some of those issues in this post