How to retrieve the post featured image (thumbnail) ID in Gutenberg blocks?

WordPress (PHP) has a lot of functionality to retrieve the post featured image (post thumbnails). However I can't f

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]' );
} ),

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]' );
} ),
Share Improve this question edited Aug 4, 2019 at 11:15 Mark asked Aug 4, 2019 at 10:02 MarkMark 1,0291 gold badge15 silver badges27 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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/WordPress/gutenberg/blob/57c2ab37a872b63de215205458336b7fd6c9739d/packages/editor/src/components/post-featured-image/index.js#L105

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745271626a4619782.html

相关推荐

  • How to retrieve the post featured image (thumbnail) ID in Gutenberg blocks?

    WordPress (PHP) has a lot of functionality to retrieve the post featured image (post thumbnails). However I can't f

    2小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信