WordPress REST API Tutorial: Add New Custom API Field

Complete WordPress REST API tutorial series link.



WordPress has become a very good option for the backend of headless applications and WP REST API made it possible. We have a wide range of options to customize this as per our application requirement. In the first article of this tutorial series, we have seen that we can get API response data for posts from http://yourwebsite.com/wp-json/wp/v2/posts this endpoint and we can get much information for a post.

But there are several occasions where we need a few more extra information related to the post such as custom metabox data or author name or other data related to the post which is not present in the API response. If you see closely to the response data then you can see that there is one field called “author” is present but is showing author id, not the name.

But we want to get the author name as well. How can we achieve this?

To get this done we need to add a new field in our REST API response and to add this we need to first register the rest field. Here’s the code for it.

Here we need to provide 3 arguments within this register_rest_field  function. For the first argument, we need to mention for which post type API response we want to add a new field. Then we need to provide the name of the field and last we have to mention an array of a callback function, which will return the value for the field.

This function will register the new field but only adding this code in our plugin or theme functions.php  file will not output the field in our response data. To make this work properly we need to wrap this within another PHP function and that function will call upon an action hook called rest_api_init

So, the final code for our desired output will be

After adding this code to your theme’s functions.php file you can get an extra field called “authorName” in your API response data for posts.

So this is how we can add new fields to API response.

If you have any question & query related to WP REST API, then comment down below.

Complete WordPress REST API tutorial series link.



 

Leave a Reply

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