easythemestore

How to Add a “Table of Contents” Automatically in WordPress

How to Add a Table of Contents Automatically in WordPress

Adding a Table of Contents (TOC) improves user experience, boosts SEO, and helps readers navigate long posts. Here are 3 easy methods to automatically generate a TOC in WordPress:


Method 1: Using a Plugin (Easiest)

Best Plugins:

  1. Easy Table of Contents (Lightweight & customizable)
  2. LuckyWP Table of Contents (Gutenberg-friendly)
  3. Rank Math (Built-in TOC block) (SEO plugin bonus)

Steps (Using Easy Table of Contents):

  1. Install & activate the plugin
  2. Go to Settings → Table of Contents
  3. Configure settings:
    • Enable for specific post types (posts, pages)

    • Set minimum headings (e.g., show TOC if 3+ H2s exist)

    • Customize position (before content, floating sidebar)

    • Style colors, fonts, and visibility

  4. Save – TOC now appears automatically in qualifying posts! Our YouTube channel; https://www.youtube.com/@easythemestore


Method 2: Using Rank Math (SEO Plugin)

If you use Rank Math, its TOC block requires no extra plugin:

  1. Edit a post in Gutenberg
  2. Add the “Table of Contents” block
  3. Adjust heading levels (H2, H3, etc.)
  4. Customize collapsible/smooth scrolling

Method 3: Manual Code (For Developers)

Add this to functions.php (child theme recommended):

function auto_toc($content) {
    if (is_single()) {
        $headings = preg_match_all('/<h[2-3].*?>(.*?)<\/h[2-3]>/i', $content, $matches);
        if ($headings >= 3) {
            $toc = '<div class="toc"><h2>Table of Contents</h2><ul>';
            foreach ($matches[0] as $key => $heading) {
                $slug = sanitize_title($matches[1][$key]);
                $toc .= '<li><a href="#' . $slug . '">' . $matches[1][$key] . '</a></li>';
            }
            $toc .= '</ul></div>';
            $content = $toc . $content;
        }
    }
    return $content;
}
add_filter('the_content', 'auto_toc');

Style with CSS:

.toc {
    background: #f9f9f9;
    padding: 15px;
    border-left: 3px solid #3367d6;
    margin-bottom: 20px;
}
.toc ul { list-style: none; padding-left: 0; }
.toc li { margin: 8px 0; }
.toc a { text-decoration: none; }
.toc a:hover { color: #3367d6; }

Best Practices for Table of Contents

✔ Place near the top (after intro)
✔ Link to H2/H3 headings (use anchor links)
✔ Make it sticky/floating for long posts (plugins support this)
✔ Update dynamically if headings change


Final Recommendation

  • For most usersEasy Table of Contents plugin (zero hassle)
  • For SEO focusRank Math’s TOC block
  • For developersCustom code solution

🚀 Pro Tip: Pair your TOC with internal linking to reduce bounce rates!

Which method will you try? Let us know in the comments!