最近用到的一个小东西,使用wordpress里的REST API时发现在post返回的JSON数据里只返回了特色图片的ID:featured_media,却没有直接返回图片地址,根据ID再去找地址很麻烦,所以干脆直接在接口里增加一个返回值算了。

代码如下:

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

添加到functions.php就好