How to add an HTML wrapper to a custom Block Pattern

Block patterns are registered with:

register_block_pattern( array( 
       'title'       => 'My Block Pattern' , 
       'content' => '...pattern...' 
) );

If we wrap the …pattern… with a div tag:

<div class="mywrapper">



it will show up as a classic block in the editor.

To avoid that, we can use the group block as an out of the box pattern wrapper with a custom class mywrapper:

<!-- wp:group {"className":"mywrapper"} -->
<div class="wp-block-group mywrapper">
<div class="wp-block-group__inner-container">


<!-- /wp:group -->

Theoretically one can use the custom html block as a pattern, like:

<!-- wp:html -->
<div class="mywrappper">
   <h1 class="has-text-align-center">Block 1</h1>
   <h2 class="has-text-align-center">Block 2</h2>
<!-- /wp:html -->

but not the best user experience 🙂

We can also write our own block to handle this, the InnerBlocks component supports nested blocks and in version 2 of the block api it becomes e.g.:

import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
import { InnerBlocks, useBlockProps } from '@wordpress/block-editor';

registerBlockType( 'wpse/wrapper', {
    apiVersion: 2,
    title: __( 'WPSE Wrapper', 'wpse' ),
    icon: 'text-page', 
    category: 'design', 
    edit: ( props ) => {
        const blockProps = useBlockProps( { className: 'mywrapper' } );
        return <div { ...blockProps }><InnerBlocks /></div>;
    save: ( props ) => {
        const blockProps = { className: 'mywrapper' } );
        return <div { ...blockProps }><InnerBlocks.Content /></div>;
} );

Then we can wrap the block pattern with:

<!-- wp:wpse/wrapper -->
<div class="wp-block-wpse-wrapper mywrapper">


<!-- /wp:wpse/wrapper -->

to generate a div wrapper containing the .mywrapper class.

This started as an answer here:

Similar Posts