最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - WP Rest API - How to get featured image

programmeradmin3浏览0评论

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 = "";
  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:

Any help will be appreciated.

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:

Any help will be appreciated.

Share Improve this question asked Jun 30, 2016 at 20:58 Abdul Sadik YalcinAbdul Sadik Yalcin 5571 gold badge4 silver badges8 bronze badges
Add a comment  | 

9 Answers 9

Reset to default 98

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

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 );

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

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

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

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

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 );

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

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

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

It's working fine.try

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

  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}`
     }})()
    
发布评论

评论列表(0)

  1. 暂无评论