Retrieving the featured post thumbnail in Gutenberg requires using the
@wordpress/data package to access the core editor store. You must use the
select function to call the
getEditedPostAttribute('featured_media') selector, which returns the attachment ID. This approach ensures compatibility with modern WordPress versions and avoids deprecated media library methods.
Understanding the Data Store
In the block editor environment, all post data is managed through a centralized Redux-like store. To access information about the current post, such as its title, content, or metadata, you need to interact with this store from within your component's
edit function. The primary tool for reading state without subscribing to changes is the
select function provided by
@wordpress/data.
It is crucial to distinguish between
select and
useSelect. While
useSelect is ideal for React hooks and automatic re-rendering,
select is often preferred in synchronous operations where you just need a snapshot of the current data at the moment the function executes. For retrieving the featured image ID,
select is sufficient and straightforward.
You must import the necessary modules from the
@wordpress packages. Specifically, you will need
select from
@wordpress/data and potentially
__ for translation strings if you are displaying labels. Ensure that your build process includes these dependencies so they resolve correctly during compilation.
Implementing the Selector
The core logic involves calling the correct selector method on the core store. The store name is
'core/editor'. Within this store, the method to retrieve edited attributes is
getEditedPostAttribute. This method takes a string argument representing the attribute key you wish to retrieve. For the featured image, the attribute key is
'featured_media'.
Here is the standard implementation pattern:
import { select } from '@wordpress/data';
function MyBlockEdit(props) {
// Retrieve the ID of the featured media
const featuredMediaId = select('core/editor').getEditedPostAttribute('featured_media');
// featuredMediaId will be an integer (ID) or null/undefined if not set
console.log('Featured Media ID:', featuredMediaId);
return (
<div>
<p>Featured Image ID: {featuredMediaId}</p>
{/* Your block UI */}
</div>
);
}
This code snippet demonstrates how to safely extract the ID. Note that if no featured image is assigned to the post,
featuredMediaId will be
null or
undefined. You should always check for this condition before attempting to use the ID to fetch the actual image URL or details.
If you need the full object data including URLs, sizes, and alt text, you cannot rely solely on
getEditedPostAttribute. Instead, you would need to use the
core/media store. However, for most basic tasks like checking if an image exists or passing the ID to another component, the
core/editor selector is the correct and performant choice.
Avoiding Common Pitfalls
A frequent error is trying to access the global
window.wp.media object directly. This approach is discouraged because it bypasses the React state management system and can lead to inconsistencies between what is displayed in the editor and what is saved. Always prefer the
@wordpress/data selectors.
Another mistake is using the old
getMedia selector incorrectly. In older versions of WordPress, signatures varied, but in current releases, you must ensure you are targeting the right store. Using
select('core/editor').getEditedPostAttribute('featured_media') is the stable, documented API for retrieving the ID. Do not attempt to guess internal private APIs.
Fetching Full Image Details
Once you have the ID, you might want to display the image itself or get its URL. You can achieve this by querying the
core/media store. This store contains information about all media items in the library.
import { select } from '@wordpress/data';
const featuredMediaId = select('core/editor').getEditedPostAttribute('featured_media');
if (featuredMediaId) {
const mediaDetails = select('core/media').getMedia(featuredMediaId);
if (mediaDetails) {
console.log('Image URL:', mediaDetails.source_url);
console.log('Alt Text:', mediaDetails.alt);
}
}
This two-step process—first getting the ID from the editor store, then fetching the details from the media store—is robust and follows the architectural patterns of the block editor. It ensures that you are working with validated data that reflects the current state of the post being edited.
For more complex scenarios involving dynamic lists or form controls, you may find related guidance in resources discussing React state management in WordPress. For instance, understanding how to handle selections in other contexts can help when building custom media selectors. You might also explore how to manage different configuration files in development environments to streamline your testing setup.
Handling Updates and Re-renders
Since
select provides a snapshot, it does not trigger re-renders if the featured image changes after the initial load. If your block needs to update dynamically when the user changes the featured image in the sidebar, you should use
useSelect instead.
import { useSelect } from '@wordpress/data';
function MyBlockEdit(props) {
const featuredMediaId = useSelect((select) =>
select('core/editor').getEditedPostAttribute('featured_media')
);
return (
<div>
<p>Current Featured ID: {featuredMediaId}</p>
</div>
);
}
useSelect subscribes to the store changes. Whenever the featured media ID changes, the component will re-render with the new value. This is essential for blocks that display live previews of the selected image or disable certain fields based on the presence of a thumbnail.
Choose
select for one-off reads in helper functions or save handlers. Choose
useSelect for UI elements that must reflect real-time changes in the editor interface. Mixing them up can lead to stale data in your UI or unnecessary performance overhead.
Frequently Asked Questions
Why is my featured media ID null?
The ID will be null if the post has not yet had a featured image assigned to it. This is expected behavior for new posts or drafts where the thumbnail slot is empty. You should handle this case in your code by providing a default placeholder or disabling features that require an image.
Can I use jQuery to get the featured image?
No, you should avoid using jQuery in Gutenberg blocks. The block editor runs in a React environment, and mixing jQuery DOM manipulation with React state management can cause conflicts and unpredictable behavior. Always use the
@wordpress/data selectors to interact with post data.
How do I get the full-size URL of the image?
After retrieving the media object using
select('core/media').getMedia(id), look for the
source_url property. This property typically holds the direct link to the uploaded file. If you need a specific size, check the
media_details.sizes object for keys like 'medium' or 'large'.
What is the difference between getPostAttribute and getEditedPostAttribute?
getPostAttribute retrieves the original data saved in the database, while
getEditedPostAttribute retrieves the current data in the editor, including unsaved changes. When building an edit interface, you almost always want
getEditedPostAttribute to see the latest updates made by the user.
Is it safe to access the media store synchronously?
Yes, accessing the
core/media store via
select is safe and synchronous. However, keep in mind that the media details might not be fully populated if the media item hasn't been fetched into the store yet. In most cases, the data is available immediately upon loading the editor.