0

I am trying to implement 'Load More' functionality via a button in a WordPress theme.

We are starting by displaying the first five posts using pre_get_posts in the standard WordPress query and, when the load more button is clicked, we want the next four posts to appear each time:

  • Default - first five posts load (using pre_get_posts)
  • Button click 1 - posts 6 - 9 appear
  • Button click 2 - posts 10 - 13 appear
  • Button click 3 - posts 14 - 17 appear
  • etc...

The AJAX load more button is working to some degree, however when the button is clicked for the first time, it's loading in posts 5 - 8, so post five is being duplicated (showing once when the page initially loads and again as the first post loaded via AJAX when the load more button is clicked for the first time), meaning what we're actually seeing is:

  • Default - first five posts load (using pre_get_posts)
  • Button click 1 - posts 5 - 8 appear
  • Button click 2 - posts 9 - 12 appear
  • Button click 3 - posts 13 - 16 appear
  • etc...

The WP_Query code we're using to facilitate the load more button is as follows:

$args = [
    'post_type' => 'post,
    'posts_per_page' => 4,
    'paged' => $_POST['paged'],
    'post_status' => 'publish'
];

$ajax = new WP_Query($args);

How can we stop the fifth post appearing as the first to be loaded by the load more button, and start out load more from post six, and the continue showing posts in increments of four?

I've toyed with using the offset parameter, but I don't think that's going to work, as it breaks the paged param, which I believe is essential here.

Thanks!

0

1 Answer 1

0

Your query doesn’t know anything about which posts you’ve already displayed. All it knows is that the second page of a 4 posts per page query is logically going to be posts 5-8. If you want to get a specific range of posts you should use offset instead of paged:

$args = [
    'offset'.        => absint( $_POST['offset'] ),
    'post_status'    => 'publish'
    'post_type'      => 'post',
    'posts_per_page' => 4,
];

$ajax = new WP_Query($args);

You'll just need to keep track of the appropriate offset on the front end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.