How to make Table of Content without Plugins

tob-without-pluginsMake Table of content without plugins and show all type of headings in one section. If any one click to table of content’s heading then scrolled to paragraph of heading.

Add TOC without plugins

  • First of all open your website’s theme.
  • Then open functions.php file and paste given code there.
function generate_table_of_contents($content) {
$pattern = '/<h([2-6]).*?>(.*?)<\/h\1>/';
preg_match_all($pattern, $content, $headings);

if (!empty($headings[0])) {
$toc = '<div class="toc"><h2>Table of Contents</h2><ul>';

foreach ($headings[2] as $key => $heading) {
$level = $headings[1][$key];
$slug = sanitize_title($heading);
$toc .= '<li><a href="#' . $slug . '">' . $heading . '</a></li>';
$content = str_replace($headings[0][$key], '<h' . $level . ' id="' . $slug . '">' . $heading . '</h' . $level . '>', $content);
}

$toc .= '</ul></div>';

// Insert TOC before the first heading
$content = preg_replace('/<h[2-6].*?>/', $toc . '$0', $content, 1);
}

return $content;
}

add_filter('the_content', 'generate_table_of_contents');
  • Now click to SAVE button and see table of content to all post’s before heading 2.

Hope this code will works on your custom theme. Thanks for visiting.