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.

Share the post:Tweet about this on TwitterShare on Google+2Share on Facebook0Share on LinkedIn1
I'm a senior web developer helping clients build their websites to grow businesses. Currently I'm based in Taipei, Taiwan. I write things about WordPress, AngularJS and life. Whenever you'd like to find someone to talk about these topics, just get in touch!

11 Comments

Submit a comment

Submit a comment

Your email address will not be published. Required fields are marked *