简体   繁体   中英

Wordpress PHP How to add a Load More feature by using AJAX/JQUERY

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 :-)

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);
    }
  });
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM