Custom gutenberg block development
To create a custom Gutenberg block in WordPress, follow these steps:
- Create a new plugin or use an existing one where you can add your custom block code.
- Enqueue the necessary scripts and stylesheets for Gutenberg block development in your plugin file using the
enqueue_block_editor_assets
hook. This will make sure that your block is properly styled and has access to the necessary functionality. - Define your custom block using the
registerBlockType
function. This function takes an object as its argument, which defines the block’s attributes, such as its name, icon, category, and edit and save functions. - In the edit function, use React to create the block’s user interface. This is where you’ll define the markup and behavior of your block.
- In the save function, define how the block’s content should be saved to the database. This function should return the markup that was generated in the edit function.
// Enqueue the necessary scripts and stylesheets
function my_custom_block_assets() {
wp_enqueue_script(
'my-custom-block',
plugin_dir_url( __FILE__ ) . 'block.js',
array( 'wp-blocks', 'wp-element' )
);
}
add_action( 'enqueue_block_editor_assets', 'my_custom_block_assets' );
// Define the custom block
function my_custom_block_init() {
register_block_type( 'my-plugin/my-custom-block', array(
'editor_script' => 'my-custom-block',
'attributes' => array(
'content' => array(
'type' => 'string',
'source' => 'html',
'selector' => '.my-custom-block',
),
),
'render_callback' => 'my_custom_block_render',
) );
}
add_action( 'init', 'my_custom_block_init' );
// Define the edit function
function my_custom_block_edit( props ) {
return (
<div className={ props.className }>
<h2>My Custom Block</h2>
<p>Edit the content here:</p>
<RichText
tagName="div"
className="my-custom-block"
value={ props.attributes.content }
onChange={ ( content ) => props.setAttributes( { content } ) }
/>
</div>
);
}
// Define the save function
function my_custom_block_save( props ) {
return (
<div className={ props.className }>
<RichText.Content
tagName="div"
className="my-custom-block"
value={ props.attributes.content }
/>
</div>
);
}
// Define the render function
function my_custom_block_render( props ) {
return (
<div className={ props.className }>
<h2>My Custom Block</h2>
<div className="my-custom-block" dangerouslySetInnerHTML={ { __html: props.attributes.content } } />
</div>
);
}