Extend the WordPress REST API of a post type by custom fields

- Development, PHP, Wordpress

Finally WordPress have a JSON REST API official for replace XML-RPC!

Today news is the official proposal for merge the infrastructure the v1 in WordPress 4.4 and the endpoints in the 4.5.

Actually is a plugin in the repo that works without problems: WP REST JSON API, is available also the v2 but is in development. I suggest to you to search the correct name in the repo because exist many plugins that implement their APIs or expand the official REST API.

The topic of this article is expand the result of a post type with new data, in my case from custom fields.

After an inspection of the hooks of the plugin I’ve found the right filters that parse the output of WP_Query.

That filter is json_prepare_post as we can see in the source code and have three parameter.

The $_post variable is the output that we need to edit to add our info.

I have added a new class in my plugin DaTask to alter the content parameter of REST API in case that is the post type task.

The code of my plugin about that support is https://github.com/Mte90/DaTask/blob/master/public%2Fincludes%2FDT_API_v1.php

As you can see is very simple, check the post type and add the values of my custom fields in $_post.

The use is very simple and is very powerful but that hooks or filters are not documented on the official site so the best solution is check the source code of the plugin.

A real working example of this code on http://passopasso.mte90.net/wp-json/posts?type=task

Have fun with WordPress and JSON REST API!

All the stuff released in this website, where the author is Daniele Scasciafratte, is under the GPL 2.0 license except when the resources have their licenses.

Leave a Reply