Search code examples
wordpresswordpress-gutenberggutenberg-blocks

Get attachment url using an attachment ID attribute in backend view of a Gutenberg block


If a Gutenberg block has an attachment ID attribute stored, is there are way to dynamically get the url of a specific thumbnail size using that ID?

The attribute will be stored in the block like this:

 imageID: {
     type: 'integer',
 },

And the idea is to dynamically show that image in the Gutenberg editor view.


Solution

  • I ran into this problem a few weeks ago. It had me baffled for a while but you can do it using withSelect()() and getMedia(). In a nut shell, we are going to have to get the media object from the ID that we have. Look inside that object for the thumbnail object. Then we will get the source_url property. Your file should look something like:

    // Block image preview
    const blockEdit = createElement("div", null, 
    
        // If image defined, get the source_url
        const imageThumbURL = props.imageObj ? props.imageObj.media_details.sizes.thumbnail.source_url : null
    
        createElement("img", {
            src: imageThumbURL
        })
    )
    
    // Use withSelect(x)(y) to load image url on page load
    const fieldData = withSelect( (select, props) => {
        // Get the image ID
        const imageId = props.attributes.imageID
    
        // Create "props.imageObj"
        return { 
            // If image defined, get the image "media" object
            imageObj: imageId ? select("core").getMedia(imageId) : null
        }
    })(blockEdit)
    
    wp.blocks.registerBlockType('plugin-namespace/block-name', {
        attributes: {
            imageID: {
                type: 'Number'
            }
        },
        edit: fieldData
    }
    

    The above is untested but I used that solution to allow my media item to load when the page is loaded by using it's ID. Hopefully this helps.