A Plugin-Free Table of Contents for WooCommerce Blog Posts (and the Theme Trap That Broke My First Try)
By MD Fozla Rabbi, SEO Specialist Long buying guides need a table of contents. Readers want to jump straight to the part they care about. Google sometimes shows those jump links right under your result. And on a phone,
By MD Fozla Rabbi, SEO Specialist
Long buying guides need a table of contents. Readers want to jump straight to the part they care about. Google sometimes shows those jump links right under your result. And on a phone, scrolling past ten sections to find one answer is just painful.
The usual fix is a TOC plugin. Most of them ship a settings page, a stylesheet and a script for something that fits in about 60 lines of PHP.
So here's the plugin-free version. Plus the theme trap that broke my first attempt.
Where this came from
We needed a TOC on the blog for Aureum, a streetwear brand in Bangladesh that sells through its own WooCommerce store. Fashion stores fighting for searches like online shopping in Bangladesh lean hard on content. The guides get long.
Take the formal pant price guide. It has ten H2 sections covering fabric, fit, colors and where to buy. Great for search. Rough for a reader on a small screen.
The trap: one class name, six places
My first try was a small JavaScript snippet. Find the post content, grab the headings, build a list. Simple.
It built nothing.
The theme is WoodMart. It uses the same content class, .wd-entry-content, in six places on a single post page. Two mega-menu dropdowns. The footer. The pre-footer. A popup. And, somewhere in the middle, the actual article.
document.querySelector('.wd-entry-content') returns the first match. That was a menu dropdown. No headings in there. So no TOC. Any CSS aimed at that class would have styled the menu and the footer too.
The lesson goes beyond one theme. Page builders and big themes reuse "content" wrappers everywhere. Never hook your code onto a generic theme class and hope it's the post.
The JS version works once you scope it to the article wrapper. But I'd rather do this on the server anyway.
Why server-side is better here
- The TOC links are in the HTML Google crawls. No waiting for JavaScript to run.
- No layout shift. The box is there on first paint instead of popping in a second later.
- Nothing to load. No extra script, no extra request.
- It works with JS disabled or broken by another plugin.
The snippet
Drop this into the Code Snippets plugin (set to run everywhere) or your child theme's functions.php.
<?php
/**
* Auto table of contents for single blog posts.
* Paste into Code Snippets (run everywhere) or a child theme's functions.php.
*/
add_filter('the_content', 'au_add_toc', 20);
function au_add_toc($html)
{
// the_content runs for menus, footers and popups too. Only touch the real post body.
if (!is_singular('post') || !in_the_loop() || !is_main_query()
|| get_the_ID() !== get_queried_object_id()) {
return $html;
}
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML('<?xml encoding="utf-8"?><div id="au-root">' . $html . '</div>',
LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$xpath = new DOMXPath($doc);
$headings = $xpath->query('//h2 | //h3');
if ($headings->length < 3) {
return $html; // short post, no TOC needed
}
$used = [];
$items = '';
foreach ($headings as $h) {
$text = trim($h->textContent);
$id = $h->getAttribute('id');
if ($id === '') {
$base = sanitize_title($text) ?: 'section';
$id = $base;
for ($n = 2; isset($used[$id]); $n++) {
$id = $base . '-' . $n;
}
$h->setAttribute('id', $id);
}
$used[$id] = true;
$class = $h->nodeName === 'h3' ? ' class="au-toc-sub"' : '';
$items .= '<li' . $class . '><a href="#' . esc_attr($id) . '">' . esc_html($text) . '</a></li>';
}
$toc = $doc->createDocumentFragment();
$toc->appendXML('<nav class="au-toc" aria-label="Table of contents"><details open="open">'
. '<summary>On this page</summary><ol>' . $items . '</ol></details></nav>');
$first = $xpath->query('//h2')->item(0) ?: $headings->item(0);
$first->parentNode->insertBefore($toc, $first);
$out = '';
foreach ($doc->getElementById('au-root')->childNodes as $node) {
$out .= $doc->saveHTML($node);
}
return $out;
}
How it works
The guard line is the server-side version of the same trap. the_content doesn't run only once per page. Themes push HTML blocks, widgets and popups through it too. So the function checks four things before touching anything:
- it's a single blog post
- we're inside the loop
- it's the main query
- the content being filtered belongs to the post in the URL
That last check, get_the_ID() !== get_queried_object_id(), is the one that saves you from a menu block or a footer that happens to be a post type.
DOMDocument with a UTF-8 hint. Without the <?xml encoding="utf-8"?> prefix, DOMDocument assumes Latin-1. Bangla text and the ৳ sign turn into mojibake. The prefix fixes that. And wrapping everything in <div id="au-root"> lets us pull the content back out cleanly.
Stable IDs. Each heading gets an ID from sanitize_title(), the same function WordPress uses for slugs. If a heading already has an ID, it's kept. That matters when other pages already link to #faq. Duplicate headings get -2, -3 and so on.
Short posts are skipped. Fewer than three headings and a TOC is just noise.
<details open> gives you a collapsible box for free. No JavaScript. Remove the open attribute if you'd rather have it closed by default.
Testing it without WordPress
You don't need a full WordPress install to check the logic. Stub the handful of functions it calls and feed it some HTML:
<?php
function add_filter($h, $cb) {}
function is_singular($t) { return true; }
function in_the_loop() { return true; }
function is_main_query() { return true; }
function get_the_ID() { return $GLOBALS['id']; }
function get_queried_object_id() { return 42; }
function sanitize_title($t) { return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($t)), '-'); }
function esc_attr($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
function esc_html($s) { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
require __DIR__ . '/au-toc.php';
$post = '<p>Intro with ৳ taka.</p><h2>Price by fabric</h2><p>a</p><h3>TR fabric</h3>'
. '<h2>Price by fit</h2><p>b</p><h2 id="faq">FAQ</h2><h3>TR fabric</h3>';
$GLOBALS['id'] = 42; // the real post
echo au_add_toc($post), "\n";
$GLOBALS['id'] = 7; // a menu block running through the_content
var_dump(au_add_toc($post) === $post);
The real post gets a TOC with #price-by-fabric, #tr-fabric, #price-by-fit, #faq and #tr-fabric-2. The ৳ sign survives. And the "menu block" call returns true, which means it was left completely alone.
The CSS (scoped to its own class)
Here's the fix for the trap on the styling side. The TOC has its own class, au-toc. We style that and nothing else. No .wd-entry-content, no .entry-content.
.au-toc {
border: 1px solid #111;
padding: 14px 18px;
margin: 24px 0;
background: #fff;
}
.au-toc summary { font-weight: 700; cursor: pointer; }
.au-toc ol { margin: 10px 0 0 18px; padding: 0; }
.au-toc li { margin: 6px 0; }
.au-toc .au-toc-sub { margin-left: 16px; list-style: circle; }
.au-toc a { color: #111; text-decoration: none; }
.au-toc a:hover { text-decoration: underline; }
/* Keep headings from hiding under a sticky header */
.single-post :is(h2, h3)[id] { scroll-margin-top: 90px; }
html { scroll-behavior: smooth; }
Black on white fits a monochrome store. Swap the two colors for your brand. And set scroll-margin-top to your sticky header's height or the heading lands underneath it.
A few gotchas
- Purge your cache. Page caching plugins will keep serving the old HTML until you clear them.
- Page builders vary. If a post is built with a page builder, check the output. Some builders render headings outside the normal content filter.
- Don't run two TOCs. If your SEO plugin or theme already adds one, turn that off first. Two lists in a row look broken.
-
Long H3 lists on mobile. Ten H2s with three H3s each makes a long box. Showing only H2s on small screens is a one-line CSS change: hide
.au-toc-subunder a media query.
Recap
- A TOC is 60 lines of PHP, not a plugin
- Never hook onto a generic theme content class
- Guard
the_contentso menus, footers and popups are left alone - Use the UTF-8 prefix with DOMDocument for non-Latin text
- Keep existing heading IDs so old anchor links still work
- Style your own class and nothing else
You can see the store this was built for at https://aureum.style. If your theme has a weirder content wrapper than six copies of the same class, I'd love to hear about it in the comments.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.