Extend core block in Gutenberg

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

1
1

Not a real answer alert

This sounds like a long term bad idea. You are modifying a core functionality with something which do not inherit any of the generated markup of the original block. Any later processing of the block might make assumption about the markup based on the block name, but the assumptions might be wrong and it will be hard to pinpoint why as the block has the expected name.

Just like with widgets and shortcodes, if you are going to basically fork the block you should just create a new one. Modifying a block should be done only when all you do is modifying some small aspect of it, and maybe not even then.

(I do realize that you might be just playing around, but still a new block is much more KISS compatible considering the code you show here)

Leave a Comment