• Hi! 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.

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    post.featured_media is the attachment ID. You need to make another API request to the media route, which will return JSON data for the attachment post_type which includes URLs to the actual images, organized by size. For example, if the media ID is 123, request something like example.com/wp-json/wp/v2/media/123.

    In the returned JSON under media_details.sizes are a list of registered sizes. Under each size is a file element whose value is that size image’s URL.

Viewing 1 replies (of 1 total)
  • The topic ‘How to get post featured image by post id’ is closed to new replies.