The WPFolks app is out on iPhone and Android. Free, no ads. Download on the App Store Get it on Google Play
Skip to main content
Login Join
Snippet · PHP

Automatically Add a Table of Contents to WordPress Posts

Shared by Amit Dholiya · September 24, 2026 · @the_content

12 views
1 upvote
Back to Snippets

Steps

    1. Add the PHP code to your theme’s functions.php.
    2. Save the changes.
    3. Create a blog post containing multiple <h2> headings.
    4. The Table of Contents will be added automatically before the post content.
/**
 * 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.

Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments