for a project I have to extend the core block core/cover-image. For the first basic try I came up with the following code:
PHP:
add_action('enqueue_block_editor_assets', function() {
wp_enqueue_script('hephaestus-admin-script',
get_template_directory_uri() . '/dist/js/admin.js', ['wp-blocks', 'wp-element', 'wp-edit-post'], THEME_VERSION);
});
admin.js:
function transformElement(element, blockType, attributes) {
if (blockType.name != 'core/cover-image') {
return element;
}
var newElement = wp.element.createElement(
'div',
{
className: 'wp-block-cover-image',
style: 'background-image: url(\'' + attributes.url + '\');',
},
[
wp.element.createElement(
'p',
{
className: 'wp-block-cover-image-text',
},
[
wp.element.createElement(
'span',
{
className: 'wp-block-cover-image-text-stage',
},
attributes.title
)
]
),
]
);
return newElement;
}
wp.hooks.addFilter(
'blocks.getSaveElement',
'hephaestus/modify-get-save-element',
transformElement
);
Basically this works. I can add the cover image block in the editor and the frontend output is as desired too.
But when reaccessing the site in backend, Gutenberg gives me the following error:
Block validation: Block validation failed for
core/cover-image
Expected:
<div class="wp-block-cover-image" style="background-image: url('https://xxxxxxxx/wp-content/uploads/2018/08/xxxxxxxx.jpg');"><p class="wp-block-cover-image-text"><span class="wp-block-cover-image-text-stage"></span></p></div>
Actual:
<div class="wp-block-cover-image" style="background-image: url('https://xxxxxxxx/wp-content/uploads/2018/08/xxxxxxxx.jpg');"><p class="wp-block-cover-image-text"><span class="wp-block-cover-image-text-stage">This is a test</span></p></div>
Note: image url is intentionally crossed out
Why do I get this block validation error here? I think it has something to do with the title attribute. But I can’t figure out what causes this…
Help, anyone?
Regards,
Marcus