Getting Categories With Posts In A Single WP API Request

UPDATED March 03, 2016:

Post has been updated. Now we use "rest_prepare_category" filter for this job.

UPDATED March 02, 2016: 

With the latest WP API V2 Beta12, the filter "rest_prepare_term" I used in this post no longer work and it should be changed to "rest_prepare_category". I'll update the post content ASAP.

A while back ago I wrote a post to show you how to “Adding Fields To The JSON Response Of The WP REST API“. In the first scenario why we’ll ever need to add fields to WP API, is for people who want to build an accordion menu with categories as the first level links, which when being clicked, the posts would be collapsed as the second level links.

We know we could use WP API to get a single category info, and we can also get the posts for a certain category, but unfortunately we can’t do both in a single API request.

So if there’re five categories as the first level menu, we’ll make five extra API calls when we access the posts for each category. That’s not cool.

I actually have solved the issue by adding a “posts” field to the category route in the post I just mentioned. But the solution is only for WP API V1. Obviously it’s time to update the code to work with V2.

From the gist above you can see:

  • Line 24: We use the new WP API V2 filter rest_prepare_category for this job.
  • Line 3-13: Here we just query the latest five posts in the category.
  • Line 14-20: I don’t wan’t to stuff the whole post objects into our response field, so I do a little clean-up with the extra loop.
  • Line 21: Finally, we add a new field “posts” into the category route.

I got asked about the same question recently, I think it’s about time to extract this topic from an old post and update the code to be adapted with WP API V2 too.

Hope you find this of use to you like I do. Feel free to leave a comment or just tweet me: @1fixdotio.

Until next time.

11 thoughts on “Getting Categories With Posts In A Single WP API Request”

  1. How is this changed with the new update? BREAKING CHANGE: Makes many filters dynamic based on the controller type.

    If you were using the rest_prepare_term filter, you’ll need to change it to rest_prepare_post_tag or rest_prepare_category.

    Do we simply change rest_prepare_term with rest_prepare_category?

    • Hey Michael, Thanks for the heads up! This is a positive change so we don’t have to do the preg_match by ourselves.

      I haven’t tested but I believe we can just use the format like:


      So they would be like “rest_prepare_category” or “rest_prepare_post_tag”.

      I’ll update this post ASAP after I validate them.


Leave a Comment