是的,使用 3 步方法,您可以添加额外的属性并将自定义内容插入现有块,而无需创建新块。添加附加属性后,您可以在自定义帖子模板中设置默认值,然后显示在编辑器中,例如:
第 1 步:使用Register Block Type Filter 将新的label 属性分配给现有的"core/paragraph" 块:
plugin.js:
function addLabelAttribute(settings, name) {
if (name !== 'core/paragraph') {
return settings;
}
return lodash.assign({}, settings, {
attributes: lodash.assign({}, settings.attributes, {
label: {
type: 'string',
default: ""
}
})
});
}
wp.hooks.addFilter(
'blocks.registerBlockType',
'core/paragraph',
addLabelAttribute
);
第 2 部分: 创建一个 Higher Order Component 以仅在设置标签的情况下将 <label>...<\label> 插入到 <BlockEdit> 中。 label属性的值是从props中解构出来的:
插件.js
const { createHigherOrderComponent } = wp.compose;
const { useBlockProps } = wp.blockEditor;
const withLabelOutput = createHigherOrderComponent((BlockEdit) => {
return (props) => {
const blockProps = useBlockProps();
const { attributes: { label } } = props;
if (label) {
// Add the custom label within a wrapped <BlockEdit>
return (
<div {...blockProps}>
<label>{label}</label>
<BlockEdit {...props} />
</div>
);
}
// No label set, return default <BlockEdit>
return (<BlockEdit {...props} />)
};
}, 'withLabelOutput');
wp.hooks.addFilter(
'editor.BlockEdit',
'core/paragraph',
withLabelOutput
);
参考:Block Editor Handbook > Block Filters
第 3 部分:在所需帖子/自定义帖子类型的模板中为新标签属性设置默认值:
plugin.php:
function myplugin_register_template(){
// N.B. Use a custom post type unless you want this to apply to all posts
$post_type_object = get_post_type_object('post');
$post_type_object->template = array(
array(
'core/paragraph',
array(
'placeholder' => 'Add Description...',
'label' => 'My Custom Label'
)
)
);
$post_type_object->template_lock = 'all';
}
add_action('init', 'myplugin_register_template');
(可选)为<label> 和enqueue it for the editor only 添加您自己的自定义编辑器样式,例如:
.wp-block-paragraph label{
font-weight: bold;
border-bottom: 1px solid grey;
padding-bottom: 0.5em;
display:block;
width:100%;
}
上面给出的所有代码示例都可以组合成一个插件,它在编辑器中创建一个标签,如: