How to wrap all titles generated by Gutenberg "Heading" block with <span> tag

Gutenberg is still relative new concept, so I lack experiences (and the Internet lacks good tutorials). My goal it to wrap all heading titles generated by Gutenberg's "Heading" block with the span tag. So instead following code

h2Tips and trics/h2

it renders this way

h2spanTips and trics/span/h2

How to start? It's JS or PHP job? Is there any filter family? What documentation search for on Wordpress.org?

Topic block-editor post-content filters theme-development Wordpress

Category Web


For anyone still looking, please see the accepted answer here for a good solution. Here's the snippet @krafter provided:

add_filter('render_block', function ($blockContent, $block) {

if ($block['blockName'] !== 'core/heading') {
    return $blockContent;
}           

$pattern = '/(<h[^>]*>)(.*)(<\/h[1-7]{1}>)/i';
$replacement = '$1<span>$2</span>$3';
return preg_replace($pattern, $replacement, $blockContent);
}, 10, 2);

This can be done using the blocks.getSaveElement filter as shown in the example below. I would STRONGLY caution that this has the potential for bad times. Core blocks are static blocks. This means that the output is saved to the database. If you want to remove these spans, you'll need to basically redo all of them. If the theme/plugin that introduces this is removed, then you'll have new headers without the span but the old ones will still have them.

    wp.hooks.addFilter(
    'blocks.getSaveElement',
    'wpse-368511',
    ( el, type, attributes ) => {
        if ( 'core/heading' === type.name ) {
            const { level, content } = attributes;
            switch ( level ) {
                case 2:
                    return ( <h2><span>{ content }</span></h2> );
                case 3:
                    return ( <h3><span>{ content }</span></h3> );
                case 4:
                    return ( <h4><span>{ content }</span></h4> );
                case 5:
                    return ( <h5><span>{ content }</span></h5> );
                default:
            }
        }
        return el;
    }
);

Hope this helps!

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.