Skip to content

Commit

Permalink
feat: add headingIds field method
Browse files Browse the repository at this point in the history
  • Loading branch information
evolkmann committed Oct 1, 2024
1 parent 13720db commit 33fe792
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

use Kirby\Content\Field;
use Kirby\Toolkit\Dom;
use Kirby\Toolkit\Str;

Kirby::plugin('volkmann-design-code/kirby-utils', [
'fieldMethods' => [
/**
* Add IDs to headings in a field
*/
'headingIds' => function (Field $field): Field {
if ($field->isNotEmpty() === true) {
$dom = new Dom($field->value);
$levels = [
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
];
$query = '//*[self::' . implode(' or self::', $levels) . ']';
$elements = $dom->query($query);

foreach ($elements as $element) {
$element->setAttribute('id', Str::slug($element->nodeValue));
}

$field->value = $dom->toString();
}

return $field;
},
],
]);

0 comments on commit 33fe792

Please sign in to comment.