[WP]: How to Generate a Table of Contents for Posts

Table of Contents for Posts
Table of Contents for Posts

for Functions.php

// Inject the TOC on each post.
add_filter(‘the_content’, function ($content) {
global $tableOfContents;
$tableOfContents = "
<div class=’h5′>
Table of Contents <span class=’toggle’>+ show</span>
<div class=’items’>
<div class=’item-h2′>
<a href=’#preface’>Preface</a>
$index = 1;
// Insert the IDs and create the TOC.
$content = preg_replace_callback(‘#<(h[1-6])(.*?)>(.*?)</\1>#si’, function ($matches) use (&$index, &$tableOfContents) {
$tag = $matches[1];
$title = strip_tags($matches[3]);
$hasId = preg_match(‘/id=(["\’])(.*?)\1[\s>]/si’, $matches[2], $matchedIds);
$id = $hasId ? $matchedIds[2] : $index++ . ‘-‘ . sanitize_title($title);
$tableOfContents .= "<div class=’item-$tag’><a href=’#$id’>$title</a></div>";
if ($hasId) {
return $matches[0];
return sprintf(‘<%s%s id="%s">%s</%s>’, $tag, $matches[2], $id, $matches[3], $tag);
}, $content);
$tableOfContents .= ‘</div>’;
return $content;
// Function action

function get_the_table_of_contents()
global $tableOfContents;
return $tableOfContents;


Single.php or content-single.php or…

<div id="preface" class="post-content row">
<div class="content col">
<?php the_content() ?>
<?php if (is_single()): ?>
<div class="post-toc col-auto">
<div class="wrapper">
<?= get_the_table_of_contents() ?>
<div class="placeholder"></div>
<?php endif ?>

Source: https://www.codepicky.com/wordpress-table-of-contents/

Leave a comment

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *