web developement

Creating a Dynamic Table of Contents for WordPress Posts with PHP

A table of contents (TOC) not only improves user experience by making navigation easier but also enhances SEO by structuring content for search engines. In this article, you’ll learn how to automate the creation of a dynamic TOC for WordPress posts using PHP. We’ll cover extracting headings, inserting the TOC automatically, and adding CSS/JavaScript to style and enhance the TOC.


Why a Table of Contents is Important

  1. Improves User Experience – Visitors can quickly jump to the section they find most relevant.
  2. Enhances SEO – Google favors structured and organized content.
  3. Increases Engagement – A TOC can help readers stay longer by showing content depth and making navigation seamless.

Step 1: Extracting Headings from Post Content

To generate a TOC dynamically, we need to extract headings (h2, h3, etc.) from the post content. Here’s how to do it using PHP:

function extract_headings($content) {
    preg_match_all('/<h([2-6])>(.*?)<\/h[2-6]>/', $content, $matches, PREG_SET_ORDER);
    $toc = '<ul class="toc">';
    $counter = 1;
    
    foreach ($matches as $match) {
        $id = 'section-' . $counter++;
        $level = $match[1];
        $title = $match[2];
        
        // Replace heading with anchor link
        $content = str_replace($match[0], "<h$level id='$id'>$title</h$level>", $content);
        
        // Add to TOC list
        $toc .= "<li class='toc-level-$level'><a href='#$id'>$title</a></li>";
    }
    $toc .= '</ul>';
    
    // Return modified content and TOC
    return ['toc' => $toc, 'content' => $content];
}

Step 2: Automatically Insert TOC into Posts

Now that we have the function to extract headings, we need to automatically insert the TOC at the start of the post. This can be done by hooking into the_content filter.

function add_toc_to_content($content) {
    if (is_single()) {
        $result = extract_headings($content);
        $toc = $result['toc'];
        $content = $result['content'];
        
        // Insert TOC at the beginning of the post
        $content = $toc . $content;
    }
    return $content;
}
add_filter('the_content', 'add_toc_to_content');

Step 3: Styling the Table of Contents with CSS

The TOC should be visually appealing and responsive. Here is a basic CSS snippet to style the TOC:

.toc {
    background: #f9f9f9;
    border: 1px solid #ddd;
    padding: 10px;
    margin-bottom: 20px;
}
.toc li {
    list-style: none;
    margin: 5px 0;
}
.toc a {
    text-decoration: none;
    color: #0073aa;
}
.toc a:hover {
    text-decoration: underline;
}

Step 4: Adding Smooth Scroll with JavaScript

To enhance user experience, let’s add smooth scrolling when the user clicks on TOC links.

<script>
    document.querySelectorAll('.toc a').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            const target = document.querySelector(this.getAttribute('href'));
            target.scrollIntoView({ behavior: 'smooth' });
        });
    });
</script>

Final Thoughts

With just a few lines of PHP, CSS, and JavaScript, you can automate the creation of a dynamic table of contents in WordPress. This not only improves usability but also contributes to better SEO. Customize the styles and functionality to fit the design of your site, and watch your content become more structured and accessible.

Leave a Reply

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