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, isn’t 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.
I opened a PR to bring this feature to core: https://github.com/WordPress/gutenberg/pull/24699
Hi Sören,
that is cool, thanks!
Best,
Florian
I sometimes need to access the anchor as a block attribute using parse_blocks. I do so my saving the value of the anchor as an additional custom attribute. (Saving it with the attribute name “anchor” breaks all blocks which haven't been converted yet.)
https://github.com/markhowellsmead/helpers/wiki/WordPress-block-filters#save-the-heading-blocks-clientid-as-a-block-attribute