I am using a custum gutenberg block plugin for wordpress(https://neliosoftware.com/blog/how-to-create-your-first-block-for-gutenberg/)

This block is using an image but always choosing the full size image. I would like that it chooses custom image sizes like the standard gutenberg image or gallery blocks. when browsing the web I can’t find any plugin for Guteberg with these options. Can you give me any suggestion on how to get these functionalities? Is it even possible?

Thank you for all your efforts to help me.

Best Lukas

3 s
3

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 Reply

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