简体   繁体   中英

Gutenberg - detecting changes to post featured image alt_text

I'm working on a plugin for Gutenberg. My plugin has to access the alt_text attribute of the post's featured image to search for a keyword in it. I access the featured image data like this:

const featuredId = select('core/editor').getEditedPostAttribute('featured_media');
const featuredMedia = featuredId ? select('core').getMedia(featuredId) : null;
console.log(featuredMedia.alt_text || 'no media');

When I load the editor, everything works as expected. But if I do any changes to the featured image (edit alt text, replace or remove the image) and run the scritpt afterwards, I get the unchanged data of the featured image. No errors or warnings. Doesn't matter if I execute the code from my js files or the browser's console. When I try editing the featured image once more I see changes in the Media Library, which is OK. The changes I made are available to JS after I save the edited post and refresh the page. How can I access the updated featured image earlier (right after I click "Set featured image" button)? Or is it a bug in WordPress/Gutenberg? Or am I missing something?

The default context for getMedia() is view which does not return a value for alt_text. To return the alt_text of the immediately after a featured image is set, change the context to embed :

const featuredId = select('core/editor').getEditedPostAttribute('featured_media');
const featuredMedia = featuredId ? select('core').getMedia(featuredId, { context: 'embed' }) : null;
console.log(featuredMedia.alt_text || 'no media');

The function getMedia() calls the Media REST API with any accepted parameters and returns the result. The context embed includes the alt_text in the response for images that aren't displayed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM