How to insert Table of Content in WordPress without Plugin

In this article, we will learn how to insert a Table of Content in WordPress without Plugin

Here’s some code that you can use to add a table of contents to your WordPress posts. You can add this code to your theme’s functions.php file at the end

function add_table_of_contents($content) {
    if (is_singular('post') && is_main_query()) {
        $pattern = '/<h([2-6]).*?>(.*?)<\/h[2-6]>/';
        if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
            $output = '<div class="table-of-contents">';
            $output .= '<h3>Table of Contents</h3>';
            $output .= '<ul>';
            foreach ($matches as $match) {
                $level = $match[1];
                $title = $match[2];
                $slug = sanitize_title($title);
                $output .= '<li class="toc-level-' . $level . '"><a href="#' . $slug . '">' . $title . '</a></li>';
                $content = str_replace($match[0], '<h' . $level . ' id="' . $slug . '">' . $title . '</h' . $level . '>', $content);
            $output .= '</ul>';
            $output .= '</div>';
            $content = $output . $content;
    return $content;

add_filter('the_content', 'add_table_of_contents');

The code will look like the below image once you pasted it correctly.

And finally, you will see the table of content is integrated after pasting the code in the function.php file.

In this article, we have learned how to insert the code of the table of content in the WordPress Theme’s function.php file.

Warning: Take a backup of the function.php file before updating the code, if things break we can restore the file.

Leave a Reply

Your email address will not be published. Required fields are marked *