Anchor support for dynamic blocks

For some core Gutenberg blocks, like heading, you can set an HTML anchor in the Advanced section of the block sidebar. The value defines the id attribute of the element, to make it possible to create a link that jumps directly to that element.

All you have to do during block registration is add the following code:

supports: { anchor: true, },
Code language: JavaScript (javascript)

Easy, isnt it? Yes, except we have a dynamic block. In that case, a PHP function does the rendering of the block markup for the frontend. For dynamic blocks, the above code snippet creates the input field, but we cannot access its value in the rendering function, because it is not stored as an attribute.

I found a not-so-nice workaround for that.

I return an empty div in the save function of the block so that the anchor value is saved as its id attribute.

save: () => { return <div></div>; }
Code language: JavaScript (javascript)

With that, we get the empty div with the id (if an anchor was specified) as the second parameter in our PHP render function, and can save the id value to a variable with the following line of code:

$anchor = preg_match( '/id="([^"]*)"/', $content, $matches );
Code language: PHP (php)

Now we can add the id to the wrapper element of the dynamic block.

2 reactions on »Anchor support for dynamic blocks«

Leave a Reply

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