Loading Posts using WordPress Rest API
ajax, jquery, wordpress
Solution
You should be using Pagination functionality provided by WP as given in the link here
So for fetching Posts it should be
/wp/v2/posts?per_page=7&page=1
per_page - `Number of records per page`
page - `page number - to be determined from Rest API Response as given below`
Also in the REST API Response , you will get two Header Response
X-WP-Total: the total number of records in the collection
X-WP-TotalPages: the total number of pages encompassing all available records
Hence using `X-WP-TotalPages` you would be able to know whether you have to fetch the next page or not.
Hence the code may look like
<button data-page="1" data-per-page="7">Load More </button>
<script>
var $wpURL="http://localhost/umar/api/wp-json/wp/v2/posts?";
$('#btn').on('click', function() {
var $this = $(this);
var nextPageToRetrieve = $this.data('page')+1;
var dataPerPage = $this.data('per-page');
$wpURL = $wpURL + "per_page="+ nextPageToRetrieve+"&page="+ dataPerPage;
$.ajax({
type: 'GET',
url: $wpURL,
data: { action: 'createHTML' },
function(data, textStatus, request){
request.getResponseHeader('X-WP-TotalPages');
request.getResponseHeader('X-WP-Total');
//Figure out the logic whether the next fetch should happen :)
// and disable the button if so.
},
error: function (request, textStatus, errorThrown) {
//FailSafe for WP API Failing
}
});
});
</script>
Problem
I am using WP Rest API to load Posts. I am using the following code. ``` jQuery('document').ready(function)(){ jQuery('#btn').on('click', function() { jQuery.ajax({ type: 'GET', url: "http://localhost/umar/api/wp-json/wp/v2/posts", data: { action: 'createHTML' }, success: function(data) { var obj = JSON.stringify(data); var test = jQuery.parseJSON(obj); createHTML(test); jQuery('#btn').hide(); } }); }); }); function createHTML(postData) { var ourHTMLString = ''; for(i=0; i<postData.length; i++) { ourHTMLString += '<p>' + postData[i].title.rendered + </h2>; ourHTMLString += postData[i].title.rendered; } jQuery(".entry-content").append(ourHTMLString); } ``` I have 50 posts and I want to load 7 posts at a time. So when a user clicks the "Load More" button, he should be able to load 7 posts and again the process remain to continue and at last button is hidden. What functionality I should add to achieve this?