WP REST API, query total posts in a category

To just know the number of posts in a category, its endpoint returns that number straightforward, in example:

curl http://wired.com/wp-json/wp/v2/categories/24

In the resource returned, the count field says: 486

Which is the same number the metadata says about the total number of posts, if you request the posts in that category, rather than the category itself:

curl -I http://wired.com/wp-json/wp/v2/posts?categories=24

You can read the header X-WP-Total: 486.

REST API of WordPress follows best practices in use today for APIs, among others, return metadata about a request in the headers, plus links to traverse the collection if it is possible.

There is no need to wait for an array of posts of length === 0 in order to know there are no more pages of posts.

Actually, the rest API return in headers, metadata about the number of pages and total of posts available to this same endpoint/filter.

For example, take the API of wired.com:

curl -I http://wired.com/wp-json/wp/v2/posts/

It returns three headers relevant to this question:

Link: <http://www.wired.com/wp-json/wp/v2/posts?page=2>; rel="next"
X-WP-TotalPages: 18067
X-WP-Total: 180664

As you can see, the results are consistent enough to know if you need to retrieve more posts or you have reached the end of the listing. You have X-WP-Total showing total of resources for this endpoint, X-WP-TotalPages showing number of pages with the same number of posts (default is 10, but you can request more with query argument per_page).

And the Link header gives you even more information which you can use to traverse without even storing the total number of posts before requesting more.

For example: $ curl -I http://www.wired.com/wp-json/wp/v2/posts?page=18067
Gives you this Link header:

Link: <http://www.wired.com/wp-json/wp/v2/posts?page=18066>; rel="prev"

(No next link, just as first page has not prev link).

And an intermediate page: $ curl -I http://www.wired.com/wp-json/wp/v2/posts?page=2
Gives you next and prev links:

Link: <http://www.wired.com/wp-json/wp/v2/posts?page=1>; rel="prev", <http://www.wired.com/wp-json/wp/v2/posts?page=3>; rel="next"

I’d suspect the number of posts REST API can return is more related to server capabilities, since I’ve being able to return per_page=100 without any trouble.

Leave a Comment

tech