This blog will teach us how to create a Table of Contents in WordPress without any plugins. We have seen on some websites that with the help of the Table of Contents, we get the title of our blog post highlighted. By doing this we can also give a good look to our website. But today we will see how to add a table of contents in the WordPress custom theme without a plugin.
I tell you step by step how to add a table of contents to your WordPress custom theme
First, paste the below code in the functions.php file of your Theme
// Inject the TOC on each post.
add_filter('the_content', function ($content) {
global $tableOfContents;
$tableOfContents = "
<div class='table-of-content'>
<h2> Table of Contents </h2>
<div class='items'>
<div class='item-h2'>
</div>
";
$index = 0;
$indexes = [2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0];
// Insert the IDs and create the TOC.
$content = preg_replace_callback('#<(h[1-6])(.*?)>(.*?)</\1>#si', function ($matches) use (&$index, &$tableOfContents, &$indexes) {
$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);
// Generate the prefix based on the heading value.
$prefix = '';
foreach (range(2, $tag[1]) as $i) {
if ($i == $tag[1]) {
$indexes[$i] += 1;
}
$prefix .= $indexes[$i] . '.';
}
$title = "$prefix $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></div>';
return $content;
});
add this also in functions.php
function get_the_table_of_contents()
{
global $tableOfContents;
return $tableOfContents;
}
Now we will paste this code in single.php where we want to show the table of content so that it will take the title of h1 to h6 of your post in the table of content
<?= get_the_table_of_contents() ?>
Most of the time we add the table of contents to the sidebar so that we can read our blog details page closely, where the sidebar is there, paste this code <?= get_the_table_of_contents() ?> and to give it style CSS, paste the code below You have given it, add it to style.css so that your table of content will get a nice look.
.table-of-content{
background-color: #f4f4f4;
padding: 25px; }
.table-of-content a{
color: #000;
font-size: 14px;
}
.table-of-content:hover a{
color: #000;
text-decoration: none;
} .item-h3 {
padding-left: 15px;
}
.item-h4 {
padding-left: 30px;
}
.item-h5 {
padding-left: 45px;
}
.item-h6 {
padding-left: 60px;
}
html{
scroll-behavior: smooth;
}
.click{
scroll-margin-top: 100px;
}
I hope that from this blog of mine, you have got the idea of how to add a table of contents to a WordPress Website.
One thought on “How To Create a Table Of Content In WordPress Without Plugin”