如何检索古腾堡区块中的帖子特色图像(缩略图)ID?

时间:2019-08-04 作者:Mark

WordPress(PHP)有很多功能来检索帖子特色图片(帖子缩略图)。然而,我找不到在动态块中检索帖子特色图像的简单方法。

使用PHP:

get_post_thumbnail_id(); // <-- Post Thumbnail ID
使用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]\' );
} ),

1 个回复
最合适的回答,由SO网友:birgire 整理而成

我想您正在寻找:

const featuredImageId = wp.data.select( \'core/editor\' )
    .getEditedPostAttribute( \'featured_media\' );
要获取特征图像的ID,然后获取相应媒体对象的ID,请执行以下操作:

const media = featuredImageId 
    ? wp.data.select( \'core\').getMedia( featuredImageId ) 
    : null;
例如,请参见此处的post featured image组件:

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

相关推荐