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