Search code examples
javascriptwordpressxmlhttprequestwordpress-rest-apiwp-api

WP API featured image attachment


Using WP API I am trying to get the featured image from a post but unsuccessful - here is the line of code that is not working:

ourHTMLString += postsData[i]._links[i].wp:featuredmedia[i].href.guid.rendered;

The other lines of code is working. Here is the code:

var prodCatPostsContainer = document.getElementById("prod-Cat-Posts-Container");

var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'www.example.com/wp-json/wp/v2/posts?filter[category_name]=news-and-events');
function createHTML(postsData) {
  var ourHTMLString = '';
  for (i = 0;i < postsData.length;i++) {
      ourHTMLString += postsData[i]._links[i].wp:featuredmedia[i].href.guid.rendered;
      ourHTMLString += '<h6 class="news-title"><a href="#">' + postsData[i].title.rendered + '</a></h6>' ;   
      ourHTMLString += postsData[i].content.rendered;   
  }
  prodCatPostsContainer.innerHTML = ourHTMLString;
}
ourRequest.onload = function() {
     if (ourRequest.status >= 200 && ourRequest.status < 400) {
       var data = JSON.parse(ourRequest.responseText);
       console.log(data);
       createHTML(data);
     } else {
       console.log("We connected to the server, but it returned an error.");
     }
};

ourRequest.onerror = function() {
  console.log("Connection error");
};
ourRequest.send();  


UPDATE

I have added another XMLHttpRequest to get the media featured image of the news item as per @RYAN AW recommendation, but still not working. I am unsure if I am doing this right, but I am pushing all the featured media ID's into an array, then I use the ID's in the array to make a get request, grabbing the "guid" -> "rendered" image url that I can see in JSON. Do I have to loop through this related news item mediaRequest somehow? i.e mediaRequest.open('GET', 'http://www.example.com/wp-json/wp/v2/media/' + featuredMedia[i]); Any help would be great.

var prodCatPostsContainer = document.getElementById("prod-Cat-Posts-Container");
var mediaContainer = document.getElementById("media-Container");
var featuredMedia = [];

//----------------- News Content ------------------//

var newsRequest = new XMLHttpRequest();
newsRequest.open('GET', 'http://www.example.com/wp-json/wp/v2/posts?filter[category_name]=news-and-events');

newsRequest.onload = function() {
  if (newsRequest.status >= 200 && newsRequest.status < 400) {
  var data = JSON.parse(newsRequest.responseText);    
  createNEWS(data);
  } else {
  console.log("News Request - We connected to the server, but it returned an error.");
  }
};
function createNEWS(postsData){
  var ourHTMLString = '';  
  for (i = 0;i < postsData.length;i++){
    featuredMedia.push(postsData[i].featured_media);
    ourHTMLString += '<h6 class='"news-title"'><a href="#">' + postsData[i].title.rendered + '</a></h6>' ;   
    ourHTMLString += postsData[i].content.rendered + '<br><br>';
  }
  prodCatPostsContainer.innerHTML = ourHTMLString;
}
newsRequest.onerror = function() {
  console.log("Connection error");
};
newsRequest.send();

//----------------- Media Featured Image ------------------//

var mediaRequest = new XMLHttpRequest();

mediaRequest.open('GET', 'http://www.example.com/wp-json/wp/v2/media/' + featuredMedia);
/*for (i = 0;i < featuredMedia.length;i++){   
    mediaRequest.open('GET', 'http://www.example.com/wp-json/wp/v2/media/' + featuredMedia[i]);
}*/
mediaRequest.onload = function() {
if (mediaRequest.status >= 200 && mediaRequest.status < 400) { 
    var mediaDat = JSON.parse(mediaRequest.responseText);       
    createMEDIA(mediaDat);
} else {
    console.log("Media Request - We connected to the server, but it returned an error.");
}
};
function createMEDIA(mediaData){
    var mediaHTMLString = '';
    for (i = 0;i < mediaData.length;i++){        
    mediaHTMLString += '<img src="' + mediaData[i].guid.rendered + '"/><br>'; 
  }
  mediaContainer.innerHTML = mediaHTMLString;
}
mediaRequest.onerror = function() {
  console.log("Connection error");
};
mediaRequest.send(); 

Solution

  • 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 + '>';