How to Create a Table of Contents in WordPress Programatically without Plugin

Creating a dynamic table of contents (TOC) on your website can significantly improve user experience by allowing visitors to quickly navigate through long articles or posts. This guide will walk you through implementing a TOC in WordPress or any other PHP-based website, using a combination of PHP and jQuery. Our approach involves generating the TOC programmatically based on the <h2> headings in your article and then enhancing its functionality with jQuery.

PHP Function: Generating the Table of Contents

function nt_generate_table_of_contents($article)
{

    $dom = new DOMDocument();
    $dom->loadHTML($article);

    // Find all the <h2> elements
    $headings = $dom->getElementsByTagName('h2');

    if ($headings->length > 0) {
        echo '<div class="table-of-contents">';
        echo '<h3>Table of Contents</h3>';
        echo '<ol>';

        $index = 0;
        foreach ($headings as $heading) {
            // Check if the heading has non-empty text
            $headingText = trim($heading->nodeValue);
            if (!empty($headingText)) {
                // Create an id attribute for the heading
                $id = 'heading_' . $index;
                $heading->setAttribute('id', $id);

                // Print the table of contents
                echo '<li><a href="#' . $id . '">' . $headingText . '</a></li>';
                $index++;
            }
        }

        echo '</ol>';
        echo '</div>';
    }

}

The PHP function nt_generate_table_of_contents($article) dynamically generates a TOC by parsing the HTML content of an article. Here’s a step-by-step explanation of how the function works:

  1. Load the HTML content: The function starts by creating a new DOMDocument instance and loading the HTML content of the article into it using $dom->loadHTML($article).
  2. Find all <h2> elements: It uses $dom->getElementsByTagName('h2') to find all <h2> elements within the document. These headings are assumed to be the main sections of the article that should be included in the TOC.
  3. Generate the TOC: If there are any <h2> elements found, the function generates HTML markup for the TOC. It creates a div container with a class table-of-contents, includes a heading for the TOC (<h3>Table of Contents</h3>), and starts an ordered list (<ol>) to list the sections.
  4. Assign IDs and list items: For each <h2> element found, the function checks if the heading text is non-empty, assigns a unique ID (heading_index), and then adds a list item (<li>) with a link (<a>) to the TOC. The href attribute of the link points to the ID of the corresponding heading, allowing users to navigate directly to that section when clicked.

jQuery Function: Set Title Anchors

if ($('.table-of-contents ol li a').length) {
    $('.table-of-contents ol li a').each(function (index) {
        // Get the corresponding heading ID from the table of contents link href
        var headingId = $(this).attr('href').substring(1);

        // Find the corresponding heading in the article content and set its ID
        var articleHeading = $('.article-content h2').eq(index);
        if (articleHeading.length > 0 && !articleHeading.attr('id')) {
            articleHeading.attr('id', headingId);
        }
    });
}

The jQuery function enhances the TOC by ensuring that each link in the TOC correctly corresponds to its respective heading in the article content. Here’s how it works:

  1. Iterate over TOC links: The script checks if there are any links in the TOC ($('.table-of-contents ol li a')). For each link, it retrieves the href attribute, which contains the ID of the corresponding heading.
  2. Set heading IDs: It then finds the corresponding heading in the article content that matches the index of the current TOC link. If the heading does not already have an ID, the script assigns it the ID extracted from the TOC link. This ensures that each TOC link and its corresponding article heading have matching IDs, facilitating smooth navigation.

Theme: Implementing the Solution

<?php
global $post;
nt_generate_table_of_contents($post->post_content);
?>

<div class="article-content">
    <?php wp_reset_query(); ?>
    <?php the_content(); ?>
</div>

To implement this solution on your WordPress site or any other PHP-based website, follow these steps:

  1. Integrate the PHP function: Place the nt_generate_table_of_contents function in your theme’s functions.php file or in a custom plugin. Modify the function as needed to match your site’s HTML structure and styling requirements.
  2. Apply the PHP function to your articles: Call the nt_generate_table_of_contents function wherever you want to display the TOC, passing the article’s HTML content as the argument. For WordPress, you might hook this function into the_content filter or call it directly in your theme’s template files.
  3. Add the jQuery script: Enqueue the jQuery script in your theme. This can be done by adding the script to your theme’s JavaScript file or by including it in a <script> tag in the footer of your site. Make sure jQuery is loaded on your site before this script.
  4. Style the TOC: Use CSS to style the TOC to match your site’s design. You can target the .table-of-contents class and its child elements with your CSS rules.

By following these steps, you can create a dynamic and navigable table of contents for your articles, improving the overall user experience of your site.


More Resources on the Internet

More Articles on Sparkle WP