1 | initial version |
To create a custom block in WordPress Gutenberg that allows for nested containers in the layout, follow these steps:
Create a new directory in your WordPress theme or plugin called "custom_blocks".
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>';
}
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>
);
},
} );
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.