1

WordPress (PHP) has a lot of functionality to retrieve the post featured image (post thumbnails). However I can't find easy ways to retrieve the post featured image in a dynamic block.

Using PHP:

get_post_thumbnail_id(); // <-- Post Thumbnail ID

Using WordPress REST API:

edit: withSelect( function( select ) {
    return {
        post_id: select( 'core/editor' ).getCurrentPostId(),
        post_type: select( 'core/editor' ).getCurrentPostType()
    };
} )( function ( props ) {
    wp.apiFetch( { path: '/wp/v2/' + props.post_type + 's/' + props.post_id + '?_embed' } ).then( function( post ) {
        console.log( post._embedded["wp:featuredmedia"][0].id ); // <-- Post Thumbnail ID
    } );  

    return el( 'div', null, '[Block Placeholder]' );
} ),
3

I think you're looking for:

const featuredImageId = wp.data.select( 'core/editor' )
    .getEditedPostAttribute( 'featured_media' );

to get the ID of the featured image and then for the corresponding media object:

const media = featuredImageId 
    ? wp.data.select( 'core').getMedia( featuredImageId ) 
    : null;

See e.g. here in the post featured image component:

https://github.com/WordPress/gutenberg/blob/57c2ab37a872b63de215205458336b7fd6c9739d/packages/editor/src/components/post-featured-image/index.js#L105

2
  • Your answer is better. I removed mine.
    – Mark
    Aug 4 '19 at 11:39
  • Glad to hear it was somewhat helpful
    – birgire
    Aug 4 '19 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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