Skip to content

Instantly share code, notes, and snippets.

@JayHoltslander
Last active July 25, 2020 01:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JayHoltslander/694cef23563029d8a556c9b41a1623a5 to your computer and use it in GitHub Desktop.
Save JayHoltslander/694cef23563029d8a556c9b41a1623a5 to your computer and use it in GitHub Desktop.
WP Featured image URLs in JSON REST API
// WP FEATURED IMAGE URLS in JSON API
// See: https://wordpress.stackexchange.com/a/249769/105228
//
add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
function add_thumbnail_to_JSON() {
//Add featured image
register_rest_field(
'post', // Where to add the field (Here, blog posts. Could be an array)
'featured_image_src', // Name of new field (You can call this anything)
array(
'get_callback' => 'get_image_src',
'update_callback' => null,
'schema' => null,
)
);
}
function get_image_src( $object, $field_name, $request ) {
$feat_img_array = wp_get_attachment_image_src(
$object['featured_media'], // Image attachment ID
'thumbnail', // Size. Ex. "thumbnail", "large", "full", etc..
true // Whether the image should be treated as an icon.
);
return $feat_img_array[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment