Add Simple Infinite Scrolling to Your WordPress Site

This post will show you how to do some simple infinite scrolling for WordPress — or really, with a few small tweaks, any other system for that matter. A lot of times on websites when you have multiple pages of results you will see pagination at the bottom of the page with page 1,2,3 etc. and there will often be first, next, previous and last links in there as well. WordPress does this when blog posts, search results, comments and a number of other sets of results in a WordPress site are broken up into different pages. A lot of WordPress themes will show only the “Previous Posts “and “Next Posts” links by default (referred to as “paging”) but some themes will extend functionality beyond this to full on pagination.

Not all users are super exited about having to click links continuously to go to the next page of results. What infinite scrolling does is get the content found on those pages and append it to the current page so the user never has to click on the pagination links… making for a really nice user experience. You may have seen it on other websites you have visited. This tutorial will show you how to implement it in your own WordPress site.

99% of all WordPress themes’ index.php file has a call to get_header(), get_sidebar() and get_footer() (so I’m kinda assuming yours does as well). In your WordPress theme’s index.php file place the following code right before your call to get_footer();

<div class="xhrStatus"></div>
<script type="text/javascript">
jQuery(document).ready(function($){
				
var currentPage = 2;
var containerItemSelector = "#main";
var postItemSelector = "article";

$(window).scroll(function() {
	
  if($(window).scrollTop() + $(window).height() == $(document).height()) {

    $.ajax({	
      type: "GET",
      url: "<?php echo $_SERVER["REQUEST_URI"] ?>?paged=" + currentPage,
      data: "",
      success: function(results) {
        var item = $(containerItemSelector + " > " postItemSelector, results);
        item.each(function() {
          $(containerItemSelector).append($(this));
        });
       currentPage++;

      },
      error: function(results) {
        if(results.status == 404) {
          $(".xhrStatus").html('No more posts to show...');
        }
        else {
          $(".xhrStatus").html('Error retriving posts...');
        }
      }

    });
  }

});

});
</script>

Now, there are a couple of variables that you’ll probably have to change to get infinite scrolling working properly on your site. These are the “containerItemSelector” and the “postItemSelector” variables. You can find them somewhere near the top of the above block of code. These variables tell the infinite scrolling code which container HTML DOM Element to put the next pages of posts in and giving it a wrapper for each post.

Let’s take a look at a very simple sample index.php file to illustrate what is being talked about here…

<?php get_header(); ?>

<div class="blog">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
   <div class="postContent">
      <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
      <?php the_content(); ?>   
  </div>
  <?php endwhile; ?>
  <?php else: ?>
  <div class="postContent">
    <h2>Not found</h2>
    <p>Sorry, no posts were found</p>
  </div>      
<?php endif; ?>
</div>

<?php get_sidebar(); ?>

<?php get_footer(); ?> 

So in the instance above, the div with the class “blog” is the wrapper element that we will be adding new posts to and each of those items are contained within a div with a class “postContent”. So we’d want to change our variables to the following…

var containerItemSelector = ".blog";
var postItemSelector = ".postContent";

So the entirety of the code of index.php would look like the following…

<?php get_header(); ?>

<div class="blog">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
   <div class="postContent">
      <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
      <?php the_content(); ?>   
  </div>
  <?php endwhile; ?>
  <?php else: ?>
  <div class="postContent">
    <h2>Not found</h2>
    <p>Sorry, no posts were found</p>
  </div>      
<?php endif; ?>
</div>

<?php get_sidebar(); ?>

<div class="xhrStatus"></div>
<script type="text/javascript">
jQuery(document).ready(function($){
				
var currentPage = 2;
var containerItemSelector = ".blog";
var postItemSelector = ".postContent";

$(window).scroll(function() {
	
  if($(window).scrollTop() + $(window).height() == $(document).height()) {

    $.ajax({	
      type: "GET",
      url: "<?php echo $_SERVER["REQUEST_URI"] ?>?paged=" + currentPage,
      data: "",
      success: function(results) {
        var item = $(containerItemSelector + " > " postItemSelector, results);
        item.each(function() {
          $(containerItemSelector).append($(this));
        });
       currentPage++;

      },
      error: function(results) {
        if(results.status == 404) {
          $(".xhrStatus").html('No more posts to show...');
        }
        else {
          $(".xhrStatus").html('Error retrieving posts...');
        }
      }

    });
  }
});

});
</script>
<?php get_footer(); ?> 

What the code above does is execute an AJAX call to do a “GET” on the next page of results when the user has scrolled to the bottom of the page. The URL that we are getting the results from is represented by the “url” property in the $.ajax block of code. The PHP variable of this property will get the current URL and will get ?paged=[value of the currentPage variable] appended to the end of it. The value of the currentPage variable will start at 2 (since we are already on page 1) and will be incremented every time we do a successful GET of results.

This URL is WordPress’ structure for breaking up content into different pages. If you wanted to add infinite scrolling to a site being run on another system you could use a similar technique, but you’d just have to provide the proper URL for how that system divided things up into pagination.

Note too that we have also added an extra <div> with a class of “xhrStatus” right above the start of our <script> block. We are going to use this div to provide messaging if an error occurs in trying to get the next page of results. If we have reached the end of the results and there are no more posts to show, the server will return a 404 error.

If you wanted to, you could change the HTML element where this message gets displayed. You’d simply have to edit the selector value in jQuery where the message gets outputted to the one that you want.

If you wanted to implement infinite scrolling on different pages (e.g. a page template with custom post type results), you could simply add the above code to that page as well and make any necessary modifications.

Happy scrolling!

, , , , , 9bit Studios E-Books

Like this post? How about a share?

Stay Updated with the 9bit Studios Newsletter

0 Responses to Add Simple Infinite Scrolling to Your WordPress Site

    Leave a Reply

    Your email address will not be published. Required fields are marked *