Steps
-
- Add the PHP code to your theme’s
functions.php. - Save the changes.
- Create a blog post containing multiple
<h2>headings. - The Table of Contents will be added automatically before the post content.
- Add the PHP code to your theme’s
/**
* Automatically add a Table of Contents to WordPress posts
*/
function custom_add_table_of_contents( $content ) {
if ( ! is_single() || ! is_main_query() || ! in_the_loop() ) {
return $content;
}
if ( stripos( $content, '<h2' ) === false ) {
return $content;
}
$items = array();
$content = preg_replace_callback(
'/<h2([^>]*)>(.*?)</h2>/i',
function ( $matches ) use ( &$items ) {
$title = wp_strip_all_tags( $matches[2] );
$id = sanitize_title( $title );
if ( empty( $id ) ) {
$id = 'section-' . ( count( $items ) + 1 );
}
$items[] = array(
'title' => $title,
'id' => $id,
);
return '<h2' . $matches[1] . ' id="' . esc_attr( $id ) . '">' .
$matches[2] .
'</h2>';
},
$content
);
if ( empty( $items ) ) {
return $content;
}
$toc = '<div class="custom-table-of-contents">';
$toc .= '<strong>Table of Contents</strong>';
$toc .= '<ul>';
foreach ( $items as $item ) {
$toc .= '<li>';
$toc .= '<a href="#' . esc_attr( $item['id'] ) . '">';
$toc .= esc_html( $item['title'] );
$toc .= '</a>';
$toc .= '</li>';
}
$toc .= '</ul>';
$toc .= '</div>';
return $toc . $content;
}
add_filter( 'the_content', 'custom_add_table_of_contents' );
Tested on
WordPress 6.8
Reported by the author on September 24, 2026. WPFolks has not verified this.
Not tested against WordPress 7.1.3. It may still work.