Skip to content

Instantly share code, notes, and snippets.

@kiub
Created August 6, 2015 20:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kiub/380a1fccc9c94e261f7a to your computer and use it in GitHub Desktop.
Save kiub/380a1fccc9c94e261f7a to your computer and use it in GitHub Desktop.
Modifying responses in WP Rest Api. Add featured image thumbnail to the response for a custom post type (by default return ID).
// in function.php
// Modify Responses WP Rest Api
add_action( 'rest_api_init', 'featured_image_thumbnail_url' );
// Modifying Responses
function featured_image_thumbnail_url() {
// More info http://v2.wp-api.org/extending/modifying/
register_api_field(
'portfolio',
'featured_image_url',
array(
'get_callback' => 'get_featured_image_url',
'update_callback' => null,
'schema' => null,
)
);
}
/**
* Get the value of the "featured_image_url" field
*
* @param array $object Details of current post.
* @param string $field_name Name of field.
* @param WP_REST_Request $request Current request
*
* @return mixed
*/
function get_featured_image_url( $object, $field_name, $request ) {
$thumbnail_id = get_post_thumbnail_id( $object->ID );
return wp_get_attachment_image_src($thumbnail_id);
}
@kiub
Copy link
Author

kiub commented Aug 6, 2015

Now return a new key with and array for the featured image.
screen shot 2015-08-06 at 16 11 31

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