Skip to content

Instantly share code, notes, and snippets.

@tharsheblows
Last active April 18, 2018 06:30
Show Gist options
  • Save tharsheblows/f057431ba5ec111e15373f6d5f4f683e to your computer and use it in GitHub Desktop.
Save tharsheblows/f057431ba5ec111e15373f6d5f4f683e to your computer and use it in GitHub Desktop.
<?
/**
* Registers the postmeta with the rest api so it can be shown there.
*/
function mjj_why_i_object_rest_field() {
// register_rest_field will register a key across *all* object subtypes
// eg if it's registered for the 'post' object, it will show up on custom post types too
// this function is hooked onto rest_api_init so logic regarding post type isn't properly possible here
register_rest_field(
array( 'post', 'page' ), // this field will appear on posts and pages
'mjj_objections', // this is the key for the field
array(
// the function called when a request to the get endpoint is made
'get_callback' => 'mjj_why_i_object_get_cb',
// the function called when a request which contains the key 'mjj_objections' is made to the post endpoint
'update_callback' => 'mjj_why_i_object_update_cb'
)
);
}
/**
* This handles the get request for the postmeta data. It is what will set up the data in the post's JSON object.
* NOTE: this could take anything. It doesn't have to be postmeta. You could put custom table data in here and it will set it up as the value for the key used in register_rest_field.
*
* @param object $post_object The post object requested
* @param string $key The key registered with register_rest_field
* @param $request The full request
* @param string $object_type The object type *from the schema* -- to get a custom post type use the post object
* @return array The escaped value to put in the post's JSON object
*/
function mjj_why_i_object_get_cb( $post_object, $field_name, $request, $object_type ){
// It's possible to get data from anywhere here. It doesn't have to be postmeta.
// whatever is returned will be the value for the key 'mjj_objections'
return $value;
}
/**
* This handles the post request made to posts/[ID] or pages/[ID] and contains the key registered in register_rest_field.
* NOTE: This doesn't have to update to postmeta, it could go anywhere.
*
* @param $value The posted value of the key registered with register_rest_field
* @param object $post_object The current post object
* @param string $key The key registered with register_rest_field
* @param $request The full request
* @param string $object_type The object type
* @return If you return a WP_Error then it'll pick that up
*/
function mjj_why_i_object_update_cb( $value, $object, $key, $request, $object_type ){
// There is a lot of information passed through to here. Use it to update whatever needs to be updated.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment