Content & Posts PHP Intermediate

Add a Table of Contents to Long Posts

Automatically add a linked table of contents above the first heading of any post with three or more H2 or H3 headings.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 69 lines
add_filter( 'the_content', function ( string $content ): string {
	if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
		return $content;
	}

	$items = [];
	$used  = [];

	$content = preg_replace_callback(
		'#<h([23])([^>]*)>(.*?)</h\1>#is',
		function ( array $m ) use ( &$items, &$used ): string {
			$text = trim( wp_strip_all_tags( $m[3] ) );
			if ( '' === $text ) {
				return $m[0];
			}

			if ( preg_match( '/\sid=(["\'])(.*?)\1/i', $m[2], $id_match ) ) {
				$id    = $id_match[2];
				$attrs = $m[2];
			} else {
				$base = sanitize_title( $text ) ?: 'section';
				$id   = $base;
				$n    = 2;
				while ( isset( $used[ $id ] ) ) {
					$id = $base . '-' . $n++;
				}
				$attrs = ' id="' . esc_attr( $id ) . '"' . $m[2];
			}

			$used[ $id ] = true;
			$items[]     = [ 'level' => (int) $m[1], 'id' => $id, 'text' => $text ];

			return '<h' . $m[1] . $attrs . '>' . $m[3] . '</h' . $m[1] . '>';
		},
		$content
	);

	if ( count( $items ) < 3 ) {
		return $content;
	}

	$toc = '<nav class="nahnu-toc" aria-label="Table of contents"><p class="nahnu-toc__title">On this page</p><ul>';
	foreach ( $items as $item ) {
		$toc .= sprintf(
			'<li class="nahnu-toc__h%d"><a href="#%s">%s</a></li>',
			$item['level'],
			esc_attr( $item['id'] ),
			esc_html( $item['text'] )
		);
	}
	$toc .= '</ul></nav>';

	// Put the table of contents just before the first H2 or H3.
	return preg_replace( '#<h[23][\s>]#i', $toc . '$0', $content, 1 );
}, 20 );

add_action( 'wp_head', function (): void {
	if ( ! is_singular( 'post' ) ) {
		return;
	}
	echo '<style>
		.nahnu-toc{border:1px solid currentColor;border-radius:8px;padding:1rem 1.25rem;margin:1.5rem 0;opacity:.95}
		.nahnu-toc__title{font-weight:700;margin:0 0 .5rem}
		.nahnu-toc ul{margin:0;padding-left:1.1rem}
		.nahnu-toc__h3{margin-left:1rem;font-size:.95em}
		html{scroll-behavior:smooth}
		@media (prefers-reduced-motion:reduce){html{scroll-behavior:auto}}
	</style>';
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Long guides are easier to read when people can jump straight to the part they need. This snippet builds a table of contents from your headings and puts it above the first one, with no plugin and no JavaScript.

How it works

The snippet filters the_content on single posts. It finds every H2 and H3, and gives each one an id made from its text (keeping any ID the heading already has, and adding a number when two headings share a name).

If there are at least three headings, it builds a list of links to those IDs and inserts it just before the first heading. H3s are indented under their H2. A few lines of CSS style the box and turn on smooth scrolling, unless the visitor has asked for reduced motion.

Because the IDs are added in PHP, the links also work for search engines, which may show them as “jump to” links in results.

Things to watch

  • Change is_singular( 'post' ) to is_singular( [ 'post', 'page' ] ) to include pages (in both places).
  • Change 3 in count( $items ) < 3 to set how many headings a post needs.
  • If you also use “Add Anchor Links to Headings”, it will reuse these IDs.
  • If your theme has a sticky header, add scroll-margin-top to headings so they aren’t hidden under it.

How to test it

Open a post with at least three H2 headings. An “On this page” box should appear above the first heading, and each link should jump to its section.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only