WordPress AJAX Pagination with query_posts

In the end I found that it is not possible to update the pagination. The way I loaded the next lot of 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);
 });  
}

Leave a Comment