WordPress REST API里默认只返回了特色图片的id
:featured_media
,却没有返回对应的图片地址。在页面里根据id
来查找对应的图片很麻烦,因此需要增加一个新的字段 featured_image_url
来直接返回对应的特色图片。
functions.php
中添加方法
#-----------------------------------------------------------------#
# API中添加特色图片
#-----------------------------------------------------------------#
function post_fetured_image_json( $data, $post, $context ) {
$featured_image_id = $data -> data['featured_media']; // 获取图片ID
$featured_image_url = wp_get_attachment_image_src( $featured_image_id, 'original' ); // 获取图片地址
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 );