Hi,
is there a way to add anchorable IDs to headlines within a Kirby Writer field?
When using a heading block, adding that is no issue at all
<?php /** @var \Kirby\Cms\Block $block */ ?>
<<?= $level = $block->level()->or('h2') ?> id="<?= $block->text()->slug() ?>"><?= $block->text() ?></<?= $level ?>>
But I currently see no way of doing it for a writer field, as that’s stored as plain html, right?
Thanks!
Yes, the Writer’s content is stored as HTML.
You will have to either transform it in a custom field method (untested, taken from an older project):
Kirby::plugin('your/plugin', [
'fieldMethods' => [
'anchorHeadlines' => function ($field) {
$text = $field->value();
$headlines = 'h2|h3|h4';
$field->value = preg_replace_callback('!<(' . $headlines . ')>(.*?)</\\1>!s', function ($match) {
$id = Str::slug(Str::unhtml($match[2]));
return '<' . $match[1] . ' id="' . $id . '">' . $match[2] . '</' . $match[1] . '>';
}, $text);
return $field;
}
]
]);
And then use it something like this:
echo $page->text()->anchorHeadlines()
Or you could add the anchor tags with JavaScript.