Search code examples
wordpresswordpress-rest-apiwordpress-gutenberggutenberg-blocks

How to get post featured image by post id


I need some help for Gutenberg Editor.

I have a dynamic block for my custom post type. I fetched all posts from rest api, now I want to add to them their featured images. I have getEditedPostAttribute and getMedia in my HOC withSelect, but I'm not sure is it correct, because wp.data('core/editor').getEditedPostAttribute('featured_media') is always return 0, so my media object will always return null. Here is my code:

import { Component } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { withSelect } from '@wordpress/data';

class PortfolioPostsEdit extends Component {
    render() {
        const { posts, className, media } = this.props;
        return (
            <>
                {(posts && posts.length > 0) ?
                    <div className={className}>
                        {posts.map(post => (
                            <article key={post.id}>
                                <a href={post.link}>
                                    {post.title.rendered}
                                </a>
                                <div>
                                    {post.featured_media}
                                </div>
                            </article>
                        ))}
                    </div>
                : <div>{__("No Posts Found", "my-blocks")}</div>
                }
            </>
        )
    }
}

export default withSelect(
    (select, props) => {
    const { getMedia } = select( 'core' );
    const { getEditedPostAttribute } = select( 'core/editor' );
    const featuredImageId = getEditedPostAttribute( 'featured_media' );
        return {
            posts: select('core').getEntityRecords('postType', 'my_portfolio', 'per_page: 20'),
            media: featuredImageId ? getMedia( featuredImageId ) : null,
            featuredImageId,
        }
    }
)(PortfolioPostsEdit);

So how should I map or pass through my media object that I get to fetch featured image for each post? Thanks.


Solution

  • I found out that I can use _embedded. So my code become:

    export default withSelect(
    (select, props) => {
        return {
            posts: select('core').getEntityRecords('postType', 'my_portfolio', 'per_page: 20', '_embed: true')
        }
    })(PortfolioPostsEdit);
    

    Then I can get my featured image by

    post._embedded['wp:featuredmedia'][0].source_url