39

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.

9 Answers 9

88

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
5
  • 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, 2017 at 20:44
  • 1
    cons: the JSON get heavier pros: not install plugin, not call another http request -> upvote Nov 21, 2017 at 17:10
  • 1
    How should convert wp:featuredmedia to JSON? first I create wp class that contains featuredmedia. But it does not work.
    – Mahdi
    Apr 3, 2018 at 6:17
  • 4
    You can access wp: by using this notation post._embedded['wp:term']
    – ocajian
    May 15, 2018 at 8:21
  • 2
    If you use a function to create the query parameters from an array and you can't use this function without combination of key and value, you can use _embed as key and true as value.
    – sneaky
    Nov 11, 2020 at 8:11
15

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_featured_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_featured_image_json', 10, 3 );

0
8

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

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

6

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

4
  • 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? Jun 30, 2016 at 21:06
  • 1
    Its the API. Still early days. It will improve Jun 30, 2016 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. Jun 30, 2016 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, 2016 at 23:34
2

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;
}
1

Try following way ....................

URL: /wp-json/wp/v2/posts?_embed

image: json["_embedded"]["wp:featuredmedia"][0]["source_url"],

It's working fine.try

0

I installed the Yoast SEO plugin and found that the featured image URL is available in that. After URL: /wp-json/wp/v2/posts?_embed

You can find featured image in: yoast_head_json > robots > og_image > url

0
  1. Install Yoast SEO plugin

  2. Get data from wp rest api to javascript

     async function fetchPosts() {
     const responce = await fetch('https://example.com/wp-json/wp/v2/posts');
     return responce.json();}
    
  3. I am displaying 10 images in HTML (I used ID = posts in .html file)

     (async () => {
     var images = '';
     for (var i = 0; i < 10; i++) {
         var obj = `<img src = '${(await fetchPosts())[i].yoast_head_json.og_image[0].url}' width="500"></img>`;
         images += obj;
         document.getElementById('posts').innerHTML = `${images}`
     }})()
    
1
  • Maybe edit your two answers together? It looks like they're giving the same solution.
    – Rup
    Mar 2 at 15:35
0

Paste this code in your theme's functions.php file and use this key for the featured image: featured_image_url

function post_featured_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_featured_image_json', 10, 3 );

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.