Last active
July 25, 2020 01:20
-
-
Save JayHoltslander/694cef23563029d8a556c9b41a1623a5 to your computer and use it in GitHub Desktop.
WP Featured image URLs in JSON REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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