Add New Custom Field to the REST API

Learn how to add new custom fields to the REST API for obtaining customized outcomes.

The WordPress REST API lets us interact with the WordPress data without accessing the WordPress user interface. It returns data as JSON objects. The WordPress REST API provides access to all the WordPress data. In this lesson we will learn how to customize the WordPress REST API responses. This lets us add new fields or modify the raw JSON data that WordPress REST API outputs.

In certain scenarios, the desired data might be nested deep within multiple layers, posing challenges for API clients to access it easily. For instance, let’s consider the situation where we want to retrieve the name of a post’s author. Although the REST API response includes a field for the author, it only contains the ID rather than the human-readable name we seek. To address this, we can create a new property called author name and position it at the same level as the post title and link, ensuring convenient access to the desired information.

register_rest_field

The register_rest_field function adds a field to any registered endpoint like posts, pages, custom post types or users. This function is invoked using the rest_api_init action hook.

Open the file functions.php. We will create a function school_custom_rest which hooks on to the rest_api_init hook to customize the REST API and add a new property to it.

Get hands-on with 1400+ tech skills courses.