Gutenberg editor get post featured image by id

How can I show a post featured image by post id in gutenberg editor? I have a slider with latest posts and when I iterate through over posts I would like to show the post featured image as well. Here is my example snippet

  const cards = displayPosts.map( ( post, i ) => {

            console.log(post.featured_media)

             return(<div className="card" key={i}>
                    <div className="card-image">
                        <div className="image is-4by3">
                            <PostFeaturedImage
                                currentPostId = {post.id}
                                featuredImageId = {post.featured_media}
                            />
                            <div className="news__post-title">
                                <div className="title is-5">
                                    <a href={ post.link } target="_blank">{ decodeEntities( post.title.rendered.trim() ) || __( '(Untitled)' ) }</a>
                                    { displayPostDate && post.date_gmt &&
                                    <time dateTime={ format( 'c', post.date_gmt ) } className="wp-block-latest-posts__post-date">
                                        { dateI18n( dateFormat, post.date_gmt ) }
                                    </time>
                                    }
                                </div>
                            </div>

                            <div className="card-content">
                                <div className="content">
                                    <p dangerouslySetInnerHTML={ { __html: post.excerpt.rendered } }></p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>)
        })

3 Answers
3

A simple and effective approach

const editor = wp.data.select('core/editor');
const imageId = editor.getEditedPostAttribute('featured_media');
const imageObj = wp.data.select('core').getMedia(imageId);

ImageObj gives you a reasonable amount of image data to work with.

Leave a Comment