22

I'm very new to this API, in fact I've only spent couple hours on it so far. I've done my research but cannot find anything about it...

The issue is, I can't seem to get the featured image of a post. The JSON returns "featured_media: 0".

getPosts: function() {
  var burl = "http://www.example.com/wp-json/wp/v2/posts";
  var dataDiv = document.getElementById('cards');
  $.ajax({
    url: burl,
    data: data,
    type: 'GET',
    async: false,
    processData: false,
    beforeSend: function (xhr) {
      if (xhr && xhr.overrideMimeType) {
        xhr.overrideMimeType('application/json;charset=utf-8');
      }
    },
    dataType: 'json',
    success: function (data) {
      console.log(data);
      //question: data->featured_image: 0?!
      var theUl = document.getElementById('cards');
      for (var key in data) {
        //data[key]['']...
        //doing my stuff here
      }
    },
    error: function(e) {
      console.log('Error: '+e);
    }  
  });
}

I have definitely, set a featured image on the post but data returns:

featured media?

Any help will be appreciated.

1

Take a look at a plugin called Better REST API Featured Image. It adds the featured image URL to the original API response.

  • Thank you. Returns the URL which is handy. Any ideas why the plugin it self is not returning it? Am I doing something wrong or is it the API? – Abdul Sadik Yalcin Jun 30 '16 at 21:06
  • 1
    Its the API. Still early days. It will improve – Michael Cropper Jun 30 '16 at 21:08
  • 1
    Problem solved! It does actually return an ID of the image but I totally forgot I had the cache turned on! But anyway, that plugin is better as it returns the url directly. – Abdul Sadik Yalcin Jun 30 '16 at 22:14
  • @Devrim Glad you solved it! If this answer from Michael helped you, you can click the tick to the left of it to accept it to show others that this was the correct answer. :) – Tim Malone Jun 30 '16 at 23:34
60

You can get it without plugins by adding _embedas param to your query

/?rest_route=/wp/v2/posts&_embed
/wp-json/wp/v2/posts?_embed
  • this causes a problem when binding to it in an Angular binding, do to the wp: name of one of the nodes in the json path to the image. I used the plugin from the other answer, which simplifies the path to the image. – Steve Oct 9 '17 at 20:44
  • 1
    cons: the JSON get heavier pros: not install plugin, not call another http request -> upvote – Tho Vo Nov 21 '17 at 17:10
  • 1
    How should convert wp:featuredmedia to JSON? first I create wp class that contains featuredmedia. But it does not work. – Kenji Apr 3 '18 at 6:17
  • 2
    You can access wp: by using this notation post._embedded['wp:term'] – ocajian May 15 '18 at 8:21
10

I would NOT use the better rest API plugin. It did add featured images to the rest api but it also broke it.

This is the simplest solution I was able to find that actually worked. Add the following code to your functions.php:

<?php

    function post_fetured_image_json( $data, $post, $context ) {
        $featured_image_id = $data->data['featured_media']; // get featured image id
        $featured_image_url = wp_get_attachment_image_src( $featured_image_id, 'original' ); // get url of the original size

        if( $featured_image_url ) {
            $data->data['featured_image_url'] = $featured_image_url[0];
        }

        return $data;
    }
    add_filter( 'rest_prepare_post', 'post_fetured_image_json', 10, 3 );

?>
4

You can get the name of the image with this path:

array_name._embedded['wp:featuredmedia']['0'].source_url

1

I made a shortcut to my image by adding it directly to the API response.


//Add in functions.php, this hook is for  my 'regions' post type
add_action( 'rest_api_init', 'create_api_posts_meta_field' );

function create_api_posts_meta_field() {
  register_rest_field( 'regions', 'group', array(
         'get_callback'    => 'get_post_meta_for_api',
         'schema'          => null,
      )
  );
}

//Use the post ID to query the image and add it to your payload
function get_post_meta_for_api( $object ) {
  $post_id = $object['id'];
  $post_meta = get_post_meta( $post_id );
  $post_image = get_post_thumbnail_id( $post_id );      
  $post_meta["group_image"] = wp_get_attachment_image_src($post_image)[0];

  return $post_meta;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.