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 :-)
$query = new WP_Query($args);always returns the newest 5. cant you add a sort or offset?