Skip to content

Instantly share code, notes, and snippets.

@gzuzkstro
Last active March 13, 2019 15:51
Show Gist options
  • Select an option

  • Save gzuzkstro/7003b0e2f6aa74e13fde6f7a760fc473 to your computer and use it in GitHub Desktop.

Select an option

Save gzuzkstro/7003b0e2f6aa74e13fde6f7a760fc473 to your computer and use it in GitHub Desktop.
#WordPress template part that extracts the heading anchors using #regex in order to build an index to navigate through the content
<?php
$content = get_the_content();
$matches = array();
preg_match_all('/\<(h[123456]).*?\sid+\=\"([0-9a-zA-Z\-]*?)\"\s?.*?\>(.+?)\<\/\1\>/', $content, $matches, PREG_SET_ORDER);
$links = array();
foreach($matches as $match){
$links[] = array(
'id' => $match[2],
'content' => $match[3]
);
}; ?>
<div class="indexed-section">
<nav class="indexed-section__index">
<?php foreach($links as $link): ?>
<a href="#<?= $link['id'] ?>" class="indexed-section__link"><?= $link['content'] ?></a>
<?php endforeach; ?>
</nav>
<main class="indexed-section__content">
<?php the_content(); ?>
</main>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment