,

Getting WordPress Media Library images in JavaScript

Update: I’ve created a video tutorial to accompany this post.

One of my favorite PHP WordPress functions is wp_get_attachment_image. You pass it the ID of an image in your Media Library and it returns the rendered image, complete with height, width, alt text, lazy loading, responsive images, etc. It’s fantastic and one I reached for a lot when I was using a lot of ACF.

While working on a custom Gutenberg block that displays a loop of blog posts (sorry Query Loop block), I needed a way to display post thumbnails as I looped through a few blog posts inside the block editor. I was using the WordPress Data Layer to fetch the blog posts, meaning the only data I had was what’s already in the REST API response for posts. The REST API gives you the ID of the post thumbnail, but not the actual image information.

Theoretically I could extend the default REST API endpoint to include the image URL for example, or even more of the image information, like sizes and alt text (like this plugin I used to use back in the day), but then it would be serving up a ton of extra stuff all the time– not just when I need it this one time.

So instead I decided to create a tiny component that replicates wp_get_attachment_imagein JavaScript. You pass it the ID for an image in the media library, and it returns an image for you. It also takes a size prop, if that’s your jam.

There’s a few more features that could theoretically be tackled here. While I don’t need to go quite as far as the core post thumbnail block (with its read/write capabilities), I wouldn’t mind passing additional attributes, similar to the original function I was basing it on. I could also look into some error handling, adding a <figure> eement around it, and maybe using a <Spinner/> or other placeholder while it fetches the image info. I’ll be thinking about it. In the meantime, feel free to use this next time you’re pulling an image from the Media Library (or send me suggestions for improvements).

For a more in-depth tutorial, check out Managing Images in your Custom Gutenberg Block.

Learn Modern WordPress Development

I’m sharing the best resources and tutorials for developers building in and on the block editor.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.