Ist es möglich, benutzerdefinierte Meta-Boxen zu den Standardblöcken in Gutenberg hinzuzufügen? Ich müsste jedem Block ein benutzerdefiniertes Datenattribut hinzufügen. Dieses Datenattribut wird dann im Frontend auf das Wrapper-Element gedruckt. Ich habe keine Dokumentation dazu finden können.
Mit filters können wir die Requisiten und Attribute von Blöcken ändern. Zuerst erweitern wir die Attribute um das neue Attribut:
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
);
Anschließend erweitern wir die Bearbeitungsfunktion des Blocks um ein Steuerelement zum Ändern des Attributs:
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);
Schließlich erweitern wir die der Speicherfunktion zugewiesenen Requisiten und fügen das Datenattribut mit dem zusätzlichen Attributwert hinzu:
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
);