Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- I have found an answer https:\\wordpress.stackexchange.com/questions/241271/wp-rest-api-details-of-latest-post-including-featured-media-url-in-one-request I added this code to my functions file in the GET request location
- add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
- function add_thumbnail_to_JSON() {
- //Add featured image
- register_rest_field('post',
- 'featured_image_src', //NAME OF THE NEW FIELD TO BE ADDED - 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'], 'thumbnail', true);
- return $feat_img_array[0];
- }
- then called ourHTMLString += '<img src=' + postsData[i].featured_image_src + '>';
- ==============================
- Ah I just had this problem myself! And while _embed is great, in my experience it is very slow, and the point of JSON is to be fast :D
- I have the following code in a plugin (used for adding custom post types), but I imagine you could put it in your theme's function.php file.
- php
- 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];
- }
- Now in your JSON response you should see a new field called "featured_image_src": containing a url to the thumbnail.
- Read more about modifying responses here:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement