Skip to content

Instantly share code, notes, and snippets.

@misfist
Last active June 19, 2016 22:04
Show Gist options
  • Save misfist/704167e17934241a59598f65a98949d4 to your computer and use it in GitHub Desktop.
Save misfist/704167e17934241a59598f65a98949d4 to your computer and use it in GitHub Desktop.
/**
* Add the field "spaceship" to REST API responses for posts read and write
*/
add_action( 'rest_api_init', 'slug_register_spaceship' );
function slug_register_spaceship() {
register_rest_field( 'post',
'starship',
array(
'get_callback' => 'slug_get_spaceship',
'update_callback' => 'slug_update_spaceship',
'schema' => null,
)
);
}
/**
* Handler for getting custom field data.
*
* @since 0.1.0
*
* @param array $object The object from the response
* @param string $field_name Name of field
* @param WP_REST_Request $request Current request
*
* @return mixed
*/
function slug_get_spaceship( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], $field_name );
}
/**
* Handler for updating custom field data.
*
* @since 0.1.0
*
* @param mixed $value The value of the field
* @param object $object The object from the response
* @param string $field_name Name of field
*
* @return bool|int
*/
function slug_update_spaceship( $value, $object, $field_name ) {
if ( ! $value || ! is_string( $value ) ) {
return;
}
return update_post_meta( $object->ID, $field_name, strip_tags( $value ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment