Creating Custom Gutenberg Blocks in WordPress
WordPress Gutenberg editor provides a flexible way to create content with blocks. If you want to extend the editor functionality by creating custom blocks, you can do so by following these steps:
Step 1: Set up Your Plugin Structure
myplugin/
│
├── myplugin.php
└── blocks/
└── my-custom-block/
├── block.js
├── editor.css
├── editor.scss
└── index.js
Step 2: Register Your Custom Block
function flashify_register_custom_block() {
wp_register_script(
'flashify-custom-block',
plugins_url( 'blocks/my-custom-block/block.js', __FILE__ ),
array( 'wp-blocks', 'wp-editor', 'wp-components' )
);
register_block_type( 'flashify/custom-block', array(
'editor_script' => 'flashify-custom-block',
) );
}
add_action( 'init', 'flashify_register_custom_block' );
Step 3: Create Your Custom Block
const { registerBlockType } = wp.blocks;
const { RichText } = wp.editor;
registerBlockType( 'flashify/custom-block', {
title: 'Custom Block',
icon: 'smiley',
category: 'common',
attributes: {
content: {
type: 'array',
source: 'children',
selector: 'p',
},
},
edit: ( { attributes, setAttributes, className } ) => {
const { content } = attributes;
const onChangeContent = ( newContent ) => {
setAttributes( { content: newContent } );
};
return (
<RichText
tagName="p"
className={ className }
value={ content }
onChange={ onChangeContent }
/>
);
},
save: ( { attributes } ) => {
return <RichText.Content tagName="p" value={ attributes.content } />;
},
} );
Step 4: Style Your Custom Block
To style your custom block, you can add CSS to the editor by enqueueing the styles in the block registration function using wp_enqueue_style function.
function flashify_enqueue_block_editor_assets() {
wp_enqueue_style(
'flashify-editor-css',
plugins_url( 'blocks/my-custom-block/editor.css', __FILE__ ),
array( 'wp-edit-blocks' ),
filemtime( plugin_dir_path( __FILE__ ) . 'blocks/my-custom-block/editor.css' )
);
}
add_action( 'enqueue_block_editor_assets', 'flashify_enqueue_block_editor_assets' );
By following these steps, you can create custom Gutenberg blocks in WordPress to enhance the editing experience and provide more dynamic content options for your users.