Getting post counts from JSON API plugin for WordPress

From time to time I find myself using the JSON API plugin for WordPress – it works good, and is handy for providing connectivity with mobile apps.  Just form a query, snag the data, sort out what you need, and done.  Nice.

Except – one of the projects I’ve got involves a LOT of data.  The initial download for a user could be as much as  480k – might not seem like a lot, but when it comes to mobile download speeds, that can really slow things down.  So the first step it to see if the client needs to update at all – the easy way is to check to see how many posts are on the server and compair that with the local client.

JSON API plugin doesn’t support just getting a count for posts of a single category.  Hm.

So, a quick hack to fix that (and, potentially, could be expanded to do a few other things).  Open up jsonapi/controllers/core.php – we’ll make two changes.  First, hunt down “public function get_category_posts()”.  Below it’s closing for the function, add:

public function get_category_posts_count() {
 global $json_api;
 $category = $json_api->introspector->get_current_category();
 if (!$category) {
 $json_api->error("Not found.");
 $posts = $json_api->introspector->get_posts(array(
 'cat' => $category->id
 return $this->posts_object_result($posts, $category, 1);

(There’s only two things different in there – a new function name that adds _count to the name, and a third parameter for the post object call)

Now, scroll down to the bottom of the file and find function posts_object_result(…).  Replace it with:

protected function posts_object_result($posts, $object, $skipData = 0) {
 global $wp_query;
 // Convert something like "JSON_API_Category" into "category"
 $object_key = strtolower(substr(get_class($object), 9));
 if($skipData == 1) {
 return array(
 'count' => count($posts),
 'pages' => (int) $wp_query->max_num_pages,
 $object_key => $object
 } else {
 return array(
 'count' => count($posts),
 'pages' => (int) $wp_query->max_num_pages,
 $object_key => $object,
 'posts' => $posts

Now, to get just a count of the posts, with titles but no article data, will return something like:

{"status":"ok","count":1,"pages":1,"category":{"id":1147,"slug":"my-articles","title":"My Article","description":"","parent":0,"post_count":1}}

Piece of cake.  It could be applied to tags and just about any other item easily.

Leave a Comment