Gutenberg add a custom metabox to default blocks

Using filters we can modify the props and attributes of blocks.
First we extend the attributes to include the new attribute:

const { addFilter } = wp.hooks;

// Register/add the new attribute.
const addExtraAttribute = props => {
    const attributes = {
        ...props.attributes,
        extra_attribute: {
            type: "string",
            default: "default_value"
        }
    };

    return { ...props, attributes };
};

addFilter(
    "blocks.registerBlockType",
    "my-plugin/extra-attribute",
    addExtraAttribute
);

Then we extend the edit function of the block to include a control to modify the attribute:

const { addFilter } = wp.hooks;
const { createHigherOrderComponent } = wp.compose;
const { Fragment } = wp.element;
const { InspectorControls } = wp.editor;
const { PanelBody, TextControl } = wp.components;

const addTextControl = createHigherOrderComponent(BlockEdit => {
    return props => {
        const { attributes, setAttributes } = props;
        return (
            <Fragment>
                <BlockEdit {...props} />
                <InspectorControls>
                    <PanelBody>
                        <TextControl
                            value={attributes.extra_attribute}
                            onChange={value => {
                                setAttributes({ extra_attribute: value });
                            }}
                        />
                    </PanelBody>
                </InspectorControls>
            </Fragment>
        );
    };
}, "withInspectorControl");

addFilter("editor.BlockEdit", "my-plugin/extra-attribute", addTextControl);

Finally we extend the props assigned to the save function and include the data attribute with the added attribute value:

const { addFilter } = wp.hooks;

// Add extra props. Here we assign an html
// data-attribute with the extra_attribute value.
const addExtraData = (props, block_type, attributes) => {
    return {
        ...props,
        "data-extra": attributes.extra_attribute
    }
};

addFilter(
    "blocks.getSaveContent.extraProps",
    "my-plugin/extra-attribute",
    addExtraData
);

Leave a Comment