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

jvs
  • 53
  • 2
  • 5

2 Answers2

4

WP_Query gives you what you want in the response headers.

The terms you are looking for are X-WP-Total and X-WP-TotalPages.

In jQuery you get the AJAX response headers like so:

$.ajax({
  url: myURL,
  success: function(data, textStatus, request){
    console.log("This is the header you're looking for",request.getResponseHeader('X-WP-Total'));
  }
});

Note I didn't have the opportunity to test this properly as I'm not by my dev machine

Design by Adrian
  • 2,185
  • 1
  • 20
  • 22
0

You can get total pages from "X-WP-TotalPages" HTTP header of http response. For example, using curl for testing from command line:

curl -i http://example.com/wp-json/posts

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.

inix
  • 485
  • 1
  • 5
  • 12
  • OP is using the REST api and JavaScript. CURL is not an option. – Design by Adrian Jun 28 '15 at 18:20
  • @DesignbyAdrian hi,maybe I want express is that you can get total-pages from response header,I use curl just for example,you need to get this value in code by yourself.I will edit this answer. – inix Jul 05 '15 at 06:45