← back to code snippets


WordPress infinite scroll

Posted on July 17th, 2014 in PHP, WordPress by Graeme

I have a list checkbox categories, which when checked, use WordPress’s admin-ajax.php to filter posts to the selected category. Now I want to build an infinite scroll type behaviour to load the next lot of posts. I found that to load the next lot of posts, the pagination will no longer work.

The way I loaded the next x posts was by setting a post offset, and using a load more button.

So in your ajax call where you are loading more posts, you need to pass over an offset value:

$.ajax({
     url: '/wp-admin/admin-ajax.php', 
     type: "POST",
     data: {
            'action': 'filter_posts',
            'selected_options':selected_options,
            'offset':postoffset
       }//etc...

Because this offset value will always change, you need to store the value in a variable. Above, I have used ‘postoffset’

The way you need to determine the value of the offset is simple. You can just use jquery to count how many posts are currently on the page:

    var postoffset = $('.hentry').length;

Where .hentry is the name of my post class.

Once you receive the post offset in your php script, you can set it like so:

 $args= array
    (
        'offset'=>$offset,
        'post_type'=>$post_type,
        'paged'=>$paged,
        'posts_per_page'=>9,
        'orderby' => 'title',
        'order' => 'ASC'
    );

and then plug that into your query_args (as well as determining the offset above, I have added a 'posts_per_page’ option which lets me clearly see the extra 9 posts loaded, and my post offset increasing by 9 each time):

$posts=query_posts( $args);

To configure your load more button instead of using the pagination, you can just put a div or picture on your page, and give it an ID - for e.g.:

<div id="load-more">LOAD MORE </div>

and the jquery:

function load_more_button_listener($){
 $('#load-more').click(function(event){
       event.preventDefault();
        var postoffset = $('.hentry').length;

 // console.log("offset: "+postoffset);

  //call the original ajax function to load more posts, with the new offset:
  load_more_posts($,postoffset);
 });  
}