1

The featured image of a post/page is not included when using REST API. Not only that, getting it is not particularly simple. This seemingly irrational fact apart, I tried to implement this answer but when fetching my page through /wp/v2/pages/?slug=my-page-name I see no new field for the featured image.

Am I missing something?

0

1 Answer 1

2

Maybe because the custom REST field (fimg_url) was only being added to posts of the post type and yet your request was for Pages, i.e. posts of the page type.. so try changing the register_rest_field( array('post') to register_rest_field( array('post', 'page').

See https://developer.wordpress.org/reference/functions/register_rest_field/#parameters.

But actually, you can use the _embed parameter to have the full media object be embedded into the response of your post/page request.

Example using JavaScript's window.fetch:

fetch( '/wp-json/wp/v2/pages?_embed' )
//fetch( '/wp-json/wp/v2/pages?_embed=wp:featuredmedia' ) // This also works.
    .then( res => res.json() )
    .then( posts => {
        posts.map( ( post ) => {
            const media = post._embedded?.['wp:featuredmedia']?.[0];

            // Default sizes, which are also the keys in mediaSizes are: full,
            // medium and thumbnail.
            const mediaSizes = media?.media_details?.sizes || {};

            console.log( mediaSizes.thumbnail?.source_url, mediaSizes );
            // Hint: Just log the `post` and `media` to see what properties are
            // there.
        } );
    } );

The above can reduce the number of HTTP requests, but it can also increase the response size, so you might instead want to use the featured_media property to request the media object via the GET /wp/v2/media/<id> endpoint. E.g.

function getFeaturedMedia( mediaId ) {
    return fetch( '/wp-json/wp/v2/media/' + mediaId ).then( res => res.json() );
}

fetch( '/wp-json/wp/v2/pages' )
    .then( res => res.json() )
    .then( posts => {
        posts.map( async ( post ) => {
            const media = post.featured_media ?
                await getFeaturedMedia( post.featured_media ) : null;

            // Default sizes, which are also the keys in mediaSizes are: full,
            // medium and thumbnail.
            const mediaSizes = media?.media_details?.sizes || {};

            console.log( mediaSizes.thumbnail?.source_url, mediaSizes );
        } );
    } );
1
  • 1
    PS: Sorry, I forgot to rename the getFeaturedMedia function, e.g. to restGetMediaItem..
    – Sally CJ
    Commented Feb 15 at 4:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.