How to get post featured image by post id
-
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)
Viewing 1 replies (of 1 total)
- The topic ‘How to get post featured image by post id’ is closed to new replies.