Validation error: Extending Gutenberg gallery block
I am trying to extend the Gutenberg core/gallery
block to add some new functionality to my image gallery on the frontend. I have created a separate plugin to handle this task.
I have registered my script with the following code:
function mt_enqueue_gutenberg(){
wp_enqueue_script(
'mt-gallery-block',
plugins_url( 'gallery-block.js',__FILE__),
array( 'wp-blocks', 'wp-i18n', 'wp-element' )
);
//Script and stylesheet loaded on frontend only
if(!is_admin()){
wp_enqueue_script(
'mt-gallery-frontend-script',
plugins_url( 'gallery.js', __FILE__),
array( 'mt-gallery-block' )
);
wp_enqueue_style(
'mt-gallery-frontend-style',
plugins_url( 'gallery.css', __FILE__),
array( 'mt-gallery-block' )
);
}
}
add_action( 'enqueue_block_editor_assets', 'mt_enqueue_gutenberg');
In my gallery-block.js
file I am using the blocks.getSaveElement
filter to edit the block’s HTML
-output to the frontend.
//Filter hook
wp.hooks.addFilter(
'blocks.getSaveElement',
'wpse-298225',
mt_gallerySaveElement
)
function mt_gallerySaveElement( element, blockType, attributes ) {
//returns the element without changing it, if it is not the gallery block
if ( blockType.name !== 'core/gallery' ) {
return element;
}
//Creates div element with nested img's
var newElement = wp.element.createElement(
'div',
{
'className': 'gallery-grid',
'data-total-slides': attributes.images.length
},
//Loops through each image in the gallery and creates an img-element
attributes.images.map(
function( image, index ) {
return wp.element.createElement(
'img',
{
'src': image.url,
'alt': image.alt,
'className': 'gallery-item',
'data-slide-no': index,
'data-caption': image.caption[0]
}
)
}
)
)
return newElement
}
Everything works as it is supposed to except when I reload the Gutenberg editor. When I reload the page I get a validation error and I am not allowed to edit the gallery block. (See screenshots below)
Below I have provided a screenshot of the console log after I reloaded the page:
I am pretty sure the error occurs because my output does not correspond to the expected structure of the gallery, and thus WordPress does not see any images inside the gallery block when I reload the page.
So, my question is: How can I fix this validation error?
Assuming the error is caused by the difference between my HTML
structure and the expected gallery structure: How can I make Gutenberg recognize my HTML
structure as a gallery?
Any suggestions would be highly appreciated. 😊
Leave an answer