I’m trying to add a custom field to the REST API response for my custom post type in WordPress. The field is supposed to show the value of my_custom_field. However, the custom field is not appearing in the response.
Here’s the code I’m using:
function add_custom_fields_to_rest_api() {
register_rest_field(
'my_custom_post_type',
'my_custom_field',
array(
'get_callback' => 'get_custom_field_value',
'update_callback' => null,
'schema' => null,
)
);
}
function get_custom_field_value($object, $field_name, $request) {
return get_post_meta($object->ID, $field_name, true);
}
add_action('rest_api_init', 'add_custom_fields_to_rest_api');
What am I doing wrong?
>Solution :
The issue lies in how you’re accessing the post ID in the get_custom_field_value function. The $object parameter should be treated as an array, not an object.
Here is how your code should look like:
function add_custom_fields_to_rest_api() {
register_rest_field(
'my_custom_post_type',
'my_custom_field',
array(
'get_callback' => 'get_custom_field_value',
'update_callback' => null,
'schema' => null,
)
);
}
function get_custom_field_value($object, $field_name, $request) {
return get_post_meta($object['id'], $field_name, true);
}
add_action('rest_api_init', 'add_custom_fields_to_rest_api');
In the get_custom_field_value function, $object['id'] correctly accesses the post ID. This should ensure that my_custom_field appears in the REST API response as expected.