WP API 精选图片附件

WP API featured image attachment

使用 WP API 我正在尝试从 post 获取特色图片但没有成功 - 这是不起作用的代码行:

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

其他代码行正常。这是代码:

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


更新

我添加了另一个 XMLHttpRequest 以根据@RYAN AW 的建议获取新闻项目的媒体特色图片,但仍然无法正常工作。我不确定我这样做是否正确,但我将所有特色媒体 ID 推入一个数组,然后我使用数组中的 ID 发出获取请求,获取 "guid" -> "rendered" 图片 url 我可以在 JSON 中看到。我是否必须以某种方式遍历此相关新闻项 mediaRequest?即 mediaRequest.open('GET', 'http://www.example.com/wp-json/wp/v2/media/' + featuredMedia[i]); 任何帮助都会很棒。

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

你好@roshambo 试着把它写成答案,有了那个插件你不需要为了获取特色图片的 img src 而发出第二个请求,我可以用 php 轻松获得这张特色图片,我对javascript不熟悉。但我认为你的代码应该是这样的。

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].better_featured_image.source_url; //full size
      ourHTMLString += postsData[i].better_featured_image.media_details.sizes.post-thumbnail.source_url; //thumbnail
      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();  

如果您仍然激活该插件,您可以分享您对单个 post 的 JSON 回复。如果 post 有特色图片,则该响应中将有 better_featured_image 字段。

我找到了答案https://wordpress.stackexchange.com/questions/241271/wp-rest-api-details-of-latest-post-including-featured-media-url-in-one-request我在 GET 请求位置将此代码添加到我的函数文件

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

然后打电话给ourHTMLString += '<img src=' + postsData[i].featured_image_src + '>';