WP-API : max num pages

$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.

Read More

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 🙂

Related posts

Leave a Reply

2 comments

  1. 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

  2. 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.