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
attributes.title
in the code above with a simple string (e.g."test"
) works fine and without any validation error. So I doubt that the block is expecting an emptyspan
. It seems that in the validation process the attribute title is missing or something.attributes.title.toString()
instead ofattributes.title
because from my tests just now, that is anarray
. So you got that error most likely because the React engine is expecting astring
and not anarray
. Sorry again and hopefully that works for you. =)attributes.title.toString()
doesn't help here either. It comes to exact the same error manage. Should've mentioned it that I tried that before... :( But thanks for your help! :)'editor.BlockEdit'
filter. That said, modifying the core blocks is still generally an unstable and considerably work-intensive practice prone to falling apart as Gutenberg iterates, and subject to cause issues and conflicts with other plugins if not approached very very carefully.