Gutenberg custom block plugin with custom image sizes

Yes, this can be done.

Are you using MediaUpload? Once an image is selected, MediaUpload returns that image object, which includes sizes: full, large, medium etc – this will include any custom sizes you’ve defined. Then, instead of assigned the url to the attribute, you save the url of the size you want.

This is demonstrated here http://jschof.com/gutenberg-blocks/wordpress-gutenberg-blocks-example-creating-a-hero-image-block-with-inspector-controls-color-palette-and-media-upload-part-2/
Under the heading “MediaUpload and the object it returns”

Ie in the Edit section of your Gutenberg block:

function onImageSelect(imageObject) {
    /* want to see the sizes returned? console log it */
    console.log(imageObject);
    setAttributes({
        backgroundImage: imageObject.sizes.full.url
    })
}

...

<div>
    <strong>Select a background image:</strong>
    <MediaUpload
        onSelect={onImageSelect}
        type="image"
        value={backgroundImage}
        render={({ open }) => (
            <button onClick={open}>
                Upload Image!
            </button>
        )}
    />
</div>

You may need a conditional to check if your image size is in the sizes, and if not use the full image.

Leave a Comment