我想将锚(id)支持添加到核心块。我在编辑器中尝试了以下JS代码来更改 cover 块。它将在“高级”属性下正确添加锚字段;但是重新加载编辑页面会导致此块包含意外或无效内容错误。
我还需要什么钩子?这可以轻松/优雅地做到吗?
function addBlockAnchor( settings, name ) {
if ( name !== 'core/cover' ) {
return settings;
}
return lodash.assign( {}, settings, {
supports: lodash.assign( {}, settings.supports, {
anchor: true
} ),
} );
}
wp.hooks.addFilter(
'blocks.registerBlockType',
'my-plugin/addBlockAnchor',
addBlockAnchor
);
我在@niklas上的最终代码回答:
function addBlockAnchor( settings, name ) {
if ( name !== 'core/cover' ) {
return settings;
}
lodash.assign( settings, settings, {
supports: lodash.assign( {}, settings.supports, {
anchor: true
} ),
attributes: lodash.assign( {}, settings.attributes, {
anchor: { type: 'string' }
} ),
} );
return settings;
}
wp.hooks.addFilter(
'blocks.registerBlockType',
'norpel-blocks/addBlockAnchor',
addBlockAnchor
);
答案 0 :(得分:1)
您还必须像这样将锚属性添加到块属性。未经测试,但应该可以。
const addBlockAnchor = props => {
if (props.attributes) { // Some blocks don't have attributes
props.attributes = {
...props.attributes,
anchor: {
type: 'string'
}
}
}
return props
}
wp.hooks.addFilter(
'blocks.registerBlockType',
'namespace/with-anchor',
addBlockAnchor
)