Introduction
Welcome to Day 9 of the Gutenberg development series! So far, you’ve learned how to create custom blocks and work with dynamic content. Today, we’re going to explore how to extend core blocks in Gutenberg. By extending an existing block, you can add new features or modify its functionality without building an entirely new block.
This is especially useful if you want to enhance a common block (like the Paragraph or Image block) by adding custom settings or controls.
In this guide, we’ll walk through extending the core/paragraph block by adding a new control for custom background colors. You’ll also learn how to extend other core blocks with similar techniques.
Step 1: Understanding the Gutenberg Block Filters
To extend core blocks in Gutenberg, we use block filters. These filters allow us to modify the block’s settings, attributes, or even how it is rendered.
The key filters used to extend blocks include:
blocks.registerBlockType
: Modifies the block’s settings.editor.BlockEdit
: Modifies the block’s editor interface (the “edit” function).blocks.getSaveElement
: Modifies the block’s save function.
We’ll use these filters to extend the Paragraph block and add a custom background color control.
Step 2: Adding a Custom Attribute
To extend a core block, we first need to add a new attribute to store the custom data. In this example, we’ll add a backgroundColor
attribute to the Paragraph block.
Create a new JavaScript file for extending the block. You can place this file in your theme or plugin folder.
// blocks/extend-paragraph.js
import { addFilter } from '@wordpress/hooks';
import { assign } from 'lodash';
import { __ } from '@wordpress/i18n';
// Add new attributes to the core/paragraph block
function addParagraphAttributes(settings) {
if (settings.name !== 'core/paragraph') {
return settings;
}
// Add the backgroundColor attribute
settings.attributes = assign(settings.attributes, {
backgroundColor: {
type: 'string',
default: '#ffffff',
},
});
return settings;
}
addFilter(
'blocks.registerBlockType',
'my-theme/extend-paragraph-attributes',
addParagraphAttributes
);
Explanation:
addFilter
: This is a WordPress hook that allows us to modify the block’s behavior. In this case, we’re using theblocks.registerBlockType
filter to extend the core Paragraph block.backgroundColor
: We add a new attributebackgroundColor
with a default value of white (#ffffff
).
Step 3: Extending the Block’s Edit Function
Next, we need to modify the block’s editor interface to allow users to set the background color for their paragraph blocks. We’ll add a color picker to the InspectorControls.
import { InspectorControls, PanelColorSettings } from '@wordpress/block-editor';
import { addFilter } from '@wordpress/hooks';
import { Fragment } from '@wordpress/element';
// Extend the edit function to add the background color control
function withInspectorControls(BlockEdit) {
return (props) => {
const { attributes, setAttributes, name } = props;
if (name !== 'core/paragraph') {
return <BlockEdit {...props} />;
}
const { backgroundColor } = attributes;
return (
<Fragment>
<BlockEdit {...props} />
<InspectorControls>
<PanelColorSettings
title={__('Background Color', 'my-theme')}
initialOpen={true}
colorSettings={[
{
value: backgroundColor,
onChange: (newColor) => setAttributes({ backgroundColor: newColor }),
label: __('Background Color', 'my-theme'),
},
]}
/>
</InspectorControls>
</Fragment>
);
};
}
addFilter(
'editor.BlockEdit',
'my-theme/extend-paragraph-inspector-controls',
withInspectorControls
);
Explanation:
PanelColorSettings
: We use this component to add a color picker for the background color in the block editor’s sidebar.withInspectorControls
: This function modifies the block’s edit function to include the new background color control in the InspectorControls.
Step 4: Modifying the Block’s Save Function
Now, we need to modify the block’s save function to ensure that the custom background color is applied when the block is rendered on the front end.
import { addFilter } from '@wordpress/hooks';
import { createElement } from '@wordpress/element';
// Modify the block’s save function to include the background color
function applyExtraProps(extraProps, blockType, attributes) {
if (blockType.name !== 'core/paragraph') {
return extraProps;
}
const { backgroundColor } = attributes;
if (backgroundColor) {
extraProps.style = {
...extraProps.style,
backgroundColor,
};
}
return extraProps;
}
addFilter(
'blocks.getSaveContent.extraProps',
'my-theme/extend-paragraph-save',
applyExtraProps
);
Explanation:
applyExtraProps
: This function modifies the block’s save function to include thebackgroundColor
attribute in the block’s inline styles when rendering it on the front end.
Step 5: Enqueuing the Script
Finally, you need to enqueue the JavaScript file so that WordPress loads it in the block editor. Add the following code to your theme’s functions.php
file:
function my_theme_enqueue_block_extension() {
wp_enqueue_script(
'my-theme-extend-paragraph-block',
get_template_directory_uri() . '/blocks/extend-paragraph.js',
array( 'wp-blocks', 'wp-element', 'wp-edit-post' ),
filemtime( get_template_directory() . '/blocks/extend-paragraph.js' )
);
}
add_action( 'enqueue_block_editor_assets', 'my_theme_enqueue_block_extension' );
This ensures that the script is available in the block editor, and the Paragraph block will be extended with the new background color control.
Step 6: Testing the Extended Block
- Rebuild Your Block: If you’re using a development environment, make sure to rebuild the block by running the appropriate command (like
npm run start
). - Test in the Editor: Go to the WordPress Block Editor, add a Paragraph block, and check the InspectorControls in the sidebar. You should now see the new Background Color option.
- Test on the Front End: Publish the post and view it on the front end to ensure that the background color is applied as expected.
Best Practices for Extending Core Blocks
When extending core blocks, keep the following best practices in mind:
- Avoid Overloading Blocks: Only add the necessary controls to avoid overwhelming users with too many options.
- Use Consistent UI: Follow the WordPress UI patterns and use built-in components like PanelColorSettings, ToggleControl, etc., for consistency.
- Handle Backward Compatibility: Ensure that the block works even if older attributes are missing or not defined.
Conclusion: Enhancing Existing Blocks
By extending core blocks, you can enhance their functionality without starting from scratch. This allows for greater flexibility and customization, all while maintaining the simplicity and familiarity of the existing block interface. In this article, we extended the Paragraph block with a new background color control, but you can apply the same principles to any core block to meet your needs.
In Day 10, we’ll explore reusable blocks and how to create custom block collections for even more content creation flexibility.
Leave a Reply