How to get posts with featured image using WordPress API

Xuất bản

Trong

If you get posts by request to this endpoint /wp-json/wp/v2/posts, you will see the the field featured_media in the response have value is a number. This is because the featured image of a post is saved into a different table in database called media.

To get information about the featured image in the response json, you have to add _embed to the endpoint, it becomes /wp-json/wp/v2/posts?_embed. The featured image you want to get lies in the field _embedded['wp:featuredmedia'][0].

But if you just want to get some fields of the posts model (eg: id, excerpt, title, link), you might make an endpoint like this: /wp-json/wp/v2/posts?_embed=1&_fields='id,excerpt,title,link,_embedded'(The _embedded field here to contain the feature image info). But you won’t get the response as you might expect. Because the query have to look for the media id in the field _links to make another query into media table. Therefore you have to include _links to the endpoint: /wp-json/wp/v2/posts?_embed=1&_fields='id,excerpt,title,link,_links,_embedded'

Leave a Reply

Your email address will not be published. Required fields are marked *