I want to add anchor (id) support to a core block. I tried the JS code below in the editor to alter the cover block. It correctly adds the anchor field under Advanced properties; however reloading the edit page results in the This Block Contains Unexpected or Invalid Content error.
What additional hooks do I need? Is this possible to do in an easy/elegant way?
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
);
My final code with @niklas answer:
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
);
You will also have to add an anchor attribute to the blocks attributes like so. Not tested, but it should work.
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
)