Ask Your Question

Revision history [back]

To create a custom block in WordPress Gutenberg that allows for nested containers in the layout, follow these steps:

  1. Create a new directory in your WordPress theme or plugin called "custom_blocks".

  2. Within the custom_blocks directory, create a new file called "nested-container.php" and add the following code:

<?php
/**
 * Nested Container
 *
 * A custom block that allows for nested containers in the layout.
 */

 function register_nested_container_block() {
     register_block_type(
         'custom-blocks/nested-container',
         array(
             'editor_script' => 'nested-container-editor-script',
             'render_callback' => 'render_nested_container_block'
         )
     );
 }

 add_action( 'init', 'register_nested_container_block' );

 function enqueue_nested_container_editor_assets() {
     wp_enqueue_script(
         'nested-container-editor-script',
         get_template_directory_uri() . '/custom_blocks/nested-container.js',
         array( 'wp-blocks', 'wp-editor' ),
         filemtime( get_template_directory() . '/custom_blocks/nested-container.js' )
     );
 }

 add_action( 'enqueue_block_editor_assets', 'enqueue_nested_container_editor_assets' );

 function render_nested_container_block( $attributes, $content ) {
     return '<div class="nested-container">' . do_blocks( $content ) . '</div>';
 }
  1. Create a new file called "nested-container.js" within the custom_blocks directory and add the following code:
const { registerBlockType } = wp.blocks;

const { InnerBlocks } = wp.editor;

registerBlockType( 'custom-blocks/nested-container', {
    title: 'Nested Container',
    icon: 'editor-table',
    category: 'layout',
    attributes: {},
    edit: props => {
        return (
            <div className="nested-container">
                <InnerBlocks allowedBlocks={['core/columns', 'custom-blocks/nested-container']} />
            </div>
        );
    },
    save: props => {
        return (
            <div className="nested-container">
                <InnerBlocks.Content />
            </div>
        );
    },
} );
  1. Finally, enqueue the "nested-container.php" file in your theme's functions.php file or your plugin's main file:
require get_template_directory() . '/custom_blocks/nested-container.php';

With these steps, you have created a custom block in WordPress Gutenberg that allows for nested containers. The block will appear in the "Layout" category of the block editor and can be used to add nested containers to your layout.