0

I want to add a "Load more" feature to my Wordpress page by using ajax and jquery. Right now, I get five items of my data by setting posts_per_page => 5 but for some reason, when I click my Load more button, it always loads the same five items/posts, so can someone maybe tell me what I'm doing wrong?

Here is my PHP code(functions.php)

$args = array(
  'post_type' => array('news'),
  'post_status' => array('publish'),
  'posts_per_page' => 5
);

$query = new WP_Query($args);

And here is my JS code:

let news_offset = 5;
loadMore(news_offset);

$('.loadmore').on("click", e => {
  e.preventDefault();
  news_offset++;
  loadMore(news_offset);
});

function loadMore(news_offset) {
  $.ajax({
    url: "/wp-admin/admin-ajax.php",
    data: {
      action: "fetch_news",
      offset: news_offset
    },
    success: function(data) {
      // Append results to DOM
      $(".news").append(data);
    },
    error: function(errorThrown) {
      console.log(errorThrown);
    }
  });
 }

Every suggestion or kind of input is welcome :-)

1
  • 1
    i am not a wordpress person but how should wp know that you want the next five? i guess if you dont specify, $query = new WP_Query($args); always returns the newest 5. cant you add a sort or offset? Commented Aug 13, 2018 at 7:56

1 Answer 1

3

Please add offset to the WP_query

$my_offset = $_POST['offset'];  //Fetch offset from the ajax request
$args = array(
  'post_type' => array('news'),
  'post_status' => array('publish'),
  'posts_per_page' => 5,
  'offset' => $my_offset
);
$query = new WP_Query($args);

In you JS code :

let news_offset = 5;            //Start with 0 if you don't have posts on page
loadMore(news_offset);

$('.loadmore').on("click", e => {
  e.preventDefault();
  news_offset += 5;            //Increment by 5
  loadMore(news_offset);
});

function loadMore(news_offset) {
  $.ajax({
    url: "/wp-admin/admin-ajax.php",
    method: "POST",
    data: {
      action: "fetch_news",
      offset: news_offset
    },
    success: function(data) {
      // Append results to DOM
      $(".news").append(data);
    },
    error: function(errorThrown) {
      console.log(errorThrown);
    }
  });
 }
Sign up to request clarification or add additional context in comments.

2 Comments

for some reason I don't know, $my_offset = $_GET['offset'] does not work, I get a blank page :-/
I've updated the answer, Please use ajax with POST instead of GET.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.