Ask any question about WordPress here... and get an instant response.
Post this Question & Answer:
How can I add custom fields to the WordPress REST API response?
Asked on Mar 01, 2026
Answer
To add custom fields to the WordPress REST API response, you can use the `register_rest_field` function. This function allows you to register a new field for a specific post type, which will then be included in the API response.
<!-- BEGIN COPY / PASTE -->
function add_custom_fields_to_rest_api() {
register_rest_field('post', 'custom_field', array(
'get_callback' => function($post_arr) {
return get_post_meta($post_arr['id'], 'custom_field', true);
},
'update_callback' => null,
'schema' => null,
));
}
add_action('rest_api_init', 'add_custom_fields_to_rest_api');
<!-- END COPY / PASTE -->Additional Comment:
- The `register_rest_field` function is used to add custom fields to the REST API response for a specific post type, such as 'post'.
- The `get_callback` function retrieves the custom field value using `get_post_meta`.
- Ensure that the custom field key ('custom_field' in this example) matches the meta key used in your WordPress database.
- This code should be added to your theme's `functions.php` file or a custom plugin.
Recommended Links:
