Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add meta data for a CPT to the REST response. `wp-json/wp/v2/poststatus_partners?_embed`
<?php
add_action( 'rest_api_init', function() {
register_rest_field(
array( 'poststatus_partners' ),
'partner_meta',
array(
'get_callback' => 'poststatus_get_restable_field_values_for_partner_meta',
'update_callback' => 'poststatus_update_restable_field_values_for_partner_meta',
'schema' => null,
)
);
} );
/**
* Handler for getting custom field data.
* @since 2.2.0
* @param array $object The object from the response
* @param string $field_id Name of field
* @param WP_REST_Request $request Current request
* @return mixed
*/
function poststatus_get_restable_field_values_for_partner_meta( $object, $field_id, $request ) {
return array(
'button_text' => get_post_meta( $object['id'], 'ps_partner_button_text', true ),
'button_color' => get_post_meta( $object['id'], 'ps_partner_button_color', true ),
'destination_url' => get_post_meta( $object['id'], 'ps_partner_url', true ),
'partner_label' => get_post_meta( $object['id'], 'ps_partner_label', true ),
);
}
/**
* Handler for updating custom field data.
* @since 2.2.0
* @param mixed $value The value of the field
* @param object $object The object from the response
* @param string $field_id Name of field
* @return bool|int
*/
function poststatus_update_restable_field_values_for_partner_meta( $values, $object, $field_id ) {
if ( empty( $values ) || ! is_array( $values ) || 'partner_meta' !== $field_id ) {
return;
}
// Do update to values and return the updated values.
return array(
'button_text' => $updated['button_text'],
'button_color' => $updated['button_color'],
'destination_url' => $updated['destination_url'],
'partner_label' => $updated['partner_label']
);
return $updated;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment