Wrap a Gutenberg Block in a container element

If you use a Gutenberg Block, it can sometimes be useful to wrap them in a container element to further control the styling.

In my case I wanted to wrap the core HTML block in a div with custom CSS class “block-html”.

WordPress 5.0 introduces an easy way to change the output of Gutenberg Blocks by using render_block – and without touching any JavaScript at all.

/**
 * Wrap Gutenberg block with container element
 */

function wrap_my_block( $block_content, $block ) {

    if ( 'core/html' === $block['blockName'] ) {
        $block_content = '<div class="block-html">' . $block_content . '</div>';
    }

    return $block_content;

};

add_filter( 'render_block', 'wrap_my_block', 10, 2 );Code language: PHP (php)

Made with ❤️ in Switzerland