Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save onur-km/38af5f2188818d0d7287c10730044729 to your computer and use it in GitHub Desktop.
Save onur-km/38af5f2188818d0d7287c10730044729 to your computer and use it in GitHub Desktop.
How do you add custom fields defined in posts to the rest API responses in wordpress

First you need to register_rest_fields to adding custom endpoints in WP REST API JSON Response

add_action( 'rest_api_init', 'add_custom_fields' );
function add_custom_fields() {
register_rest_field(
'post', 
'custom_fields', //New Field Name in JSON RESPONSEs
array(
    'get_callback'    => 'get_custom_fields', // custom function name 
    'update_callback' => null,
    'schema'          => null,
     )
);
}

Then define your functions to get custom fields

function get_custom_fields( $object, $field_name, $request ) {
//your code goes here
return $customfieldvalue;
}

Tested on local site

enter image description here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment