Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom field doesn't show in the WordPress REST API response

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading