Skip to content

Instantly share code, notes, and snippets.

@indextwo
Created April 29, 2021 16:04
Show Gist options
  • Save indextwo/9ea113a89391b94017732e10e4ff85da to your computer and use it in GitHub Desktop.
Save indextwo/9ea113a89391b94017732e10e4ff85da to your computer and use it in GitHub Desktop.
WordPress/Gutenberg: Automatically create a list of links to anchor points in headings
<?php
// Create an array to put out anchor links into
$anchorLinks = array();
// We're going to parse out the blocks of the current page's content
$blocks = parse_blocks(get_the_content());
foreach ($blocks as $block) {
// We're only going through 'heading' blocks. Technically any(?) core Gutenberg block can have an anchor link,
// but we're sticking with headings to keep it simple.
if ($block['blockName'] == 'core/heading') {
// Only if the heading actually has an ID attr (which would indicicate it's an anchor)
if (strpos($block['innerHTML'], 'id=') !== false) {
// User preg_match() to pull out the value of the ID, which in this case is $matches[1]
preg_match('/id="([\s\S]*?)"/', $block['innerHTML'], $matches);
// Create an anchor link, with a link to the heading we've just processed, using the stripped text value
// of the heading as the text for the link.
$anchorLink = '<a href="#' . $matches[1] . '">' . wp_strip_all_tags($block['innerHTML']) . '</a>';
// Add it to our array
$anchorLinks[] = $anchorLink;
}
}
}
// Assuming the $anchorLinks array isn't empty, spit out an <ol> list of links
if (!empty($anchorLinks)) {
echo '<ol class="content-links sticky">';
foreach($anchorLinks as $link)
echo '<li>' . $link . '</li>';
echo '</ol>';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment