Categories
Gutenberg WordPress

How to add anchor support to Gutenberg blocks on WordPress

Note: If you are new to extending blocks using filters, I’d recommend giving this a read first: https://junaid.dev/how-to-extend-blocks-in-the-gutenberg-editor-on-wordpress/

Example: How to use block filters to add “Anchor” support to core columns

In this example, we are going to add anchor support to the core Columns block, but this can easily be extended to other blocks:

Explanation

We first declare the blocks we need to do this for. They can be core or custom blocks:

const blocks = [
	'core/columns',
	'someone/elses-block',
];

We then hook into the blocks.registerBlockType filter. We add anchor support to the block by adding anchor: true to the supports object.

We then append the anchor attribute to our blocks:

const attributes = {
	...props.attributes,
	anchor: {
		type: 'string',
		source: 'attribute',
		attribute: 'id',
		selector: '*',
	},
};
props = { ...props, attributes };

That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *