$opts = array(); // any arguments
$query = WP_Query($opts);
Normally, we can get max_num_pages by using $totalPages = $query->max_num_pages;
But, i make json request by using this plugin http://wp-api.org/.
When i was trying to retrieve posts using the API, the response is just json object/array of posts. The problem is, $query->max_num_pages;
isn’t accessible. I need that var to make a paginated request.
eg, i want to make a request:
$.ajax({
url: 'wp-json/posts?page=' + currentPage + '&filter[posts_per_page]=' + perPage + '&filter[cat]=' + category
});
How can we fill the currentPage
var if we don’t know the max_num_pages ? if i just fill the currentPage
with 1
, it’s ok (because assuming it was page 1). But how i know if there is page 2, page 3?
Do you have any idea? Thanks so much, for any help 🙂
WP_Query gives you what you want in the response headers.
The terms you are looking for are
X-WP-Total
andX-WP-TotalPages
.In jQuery you get the AJAX response headers like so:
You can get total pages from “X-WP-TotalPages” HTTP header of http response.
For example, using curl for testing from command line:
After you get total pages,50 pages,for example,you can loop from 1 to 50,response from above CLI also contain a useful header called “Link:”,you can get more detail from this link: http://wp-api.org/guides/getting-started.html.
You need to get this value in codes by yourself.