While working on my AngularJS for WP plugin I noticed one of the main differences between the v1 of the REST API plugin and v2 is that with v2 you had to define api fields individually per custom post type. This was easy when it comes to post creation ’cause I required users to pass in the slug for the CPT they wanted anyway, so I could route the POST request to /wp/v2/[cpt-slug] but this became really tricky when it came to getting and saving custom taxonomy data. This was a feature I had in my plugin and I wanted to keep it in the new version of my plugin.

The fix was pretty simple in concept, and maybe took me a little long to get working, but figured I’d share.

get_post_types – is a function built into WordPress and it based on criteria can spit out all of the post types that exist.

I used the code above, the only thing I could not figure out was how to NOT get attachments as a returned post type, but for now that is fine. I then looped through the return (an array of post types) registering the field.

Luckily since setting a post object’s taxonomy is done with 1 function all post types could share the same awesome callback function:

Load Order

Since WordPress has no dependency manager built in, I had to rework my plugin a bit so that it actually hooks into init vs. just normally when WordPress decides to load my plugin. Why?

I noticed that another plugin I had and was testing with did not work, and that is because it was not registered yet so get_post_types was not returning it.

Thats it!

I hope this helps someone, ’cause it took me a while to figure it out myself!

Look out for v3 of my AngularJS for WP plugin in the repo soon, or on GitHub