Search code examples
wordpresscustom-data-attributewordpress-gutenberggutenberg-blocks

wordpress gutenberg: Block validation failed for `core/image` when adding data attribute (data-id="")


Getting a Gutenberg validation error when adding the data attribute (using Edit as HTML) to the anchor tag, this issue occurring whenanchor tag inside figure tag.

When user add the image and wrap that image with link, onsubmit event our plugin scan the post content and add the data attribute to link, when refresh/reopen the post edit page again console shows a gutenberg validation error.

<figure class="wp-block-image size-large">
   <a href="http://affiliate.local/wp-admin/post.php?post=56662&amp;action=edit" data-lasso-id="123">
     <img src="http://affiliate.local/wp-content/uploads/2019/06/mint_2018_icon-toolbox-640x640.jpg" alt="" class="wp-image-51176"/>
   </a>
</figure>

enter image description here enter image description here


Solution

  • After many try and error I got my solution.

    wp.hooks.addFilter(
        "blocks.registerBlockType",
        "sample-plugin/plugin/attribute/data",
        (settings, name) => {
            if (name == "core/image") {
                settings.attributes = Object.assign( settings.attributes, {
                    'data-id': {
                        attribute: "data-id",
                        selector: "figure > a",
                        source: "attribute",
                        type: "string",
                    },
                });
            }
            return settings;
        }
    );
    
    
    function applyExtraClass( extraProps, blockType, attributes ) {
        if(blockType.name != 'core/image') {
            return extraProps;
        }
    
        try {
            let figure_props = extraProps.children.props;
            let first_child = figure_props.children[0];
            if(figure_props.children && first_child && (first_child.type == 'a')) {
                first_child.props['data-id'] = attributes["data-id"];
            }
        } catch (error) {
            console.log(error);
        }
        return extraProps;
    }
    
    wp.hooks.addFilter(
        'blocks.getSaveContent.extraProps',
        'sample-plugin/plugin',
        applyExtraClass
    );