Record multiple images through a Wordpress Gutenberg block

Asked

Viewed 44 times

-1

I’m creating a new block of Gutenberg which serves as an image gallery. The idea is that the user can upload several images through the back-office.

For the attributes I have the following:

    attributes: {
        imgURL: {
            type: 'string',
            source: 'attribute',
            attribute: 'src',
            selector: 'img'
        },
    },

Inside the Edit:

edit: function( props ) {

        const onFileSelect = (img) => {

            props.setAttributes({

                imgURL: img.url,
                imgID: img.id,
                imgAlt: img.alt

            });
        }
(...)
<MediaUpload
                            onSelect={onFileSelect}
                            value={1}
                            render= {({open}) =>
                                <Button
                                    onClick={open}
                                >
                                    Load image
                                </Button>
                            }
                        />

For an image works well but I wanted the code to be dynamic. What will be the best approach ?

  • if the answer is right, don’t forget to mark as right @joão-dessain-saraiva

1 answer

0

You have to create a function that collects all the gallery ids.

I leave you here a control that you can use, the name I gave to attr was gallery, you have to define it before the Return inside the render method()

<MediaUpload
onSelect={( images ) => {
    const imagesList = images.map( ( image ) => {
        return {
            id: image.id,
            url: image.url
        };
    } );
    this.props.setAttributes( { gallery: JSON.stringify( imagesList ) } );
}}
allowedTypes={['image']}
value={gallery !== '' ? gallery.map( ( image ) => image.id ) : ''}
multiple
gallery
render={( { open } ) => (
    <IconButton
        label={__( 'Alterar Gallery' )}
        icon="format-image"
        onClick={open}
    />
)} />

The code of Attributes:

'gallery' => [
    'type'    => 'string',
    'default' => '',
],

Browser other questions tagged

You are not signed in. Login or sign up in order to post.