..., 'toc' => ...] */ public static function process( $content ) { if ( empty( $content ) ) return array( 'content' => $content, 'toc' => '' ); $headings = array(); $counter = array(); // Add IDs to h2, h3, h4 $content = preg_replace_callback( '/<(h[234])([^>]*)>(.*?)<\/h[234]>/si', function( $matches ) use ( &$headings, &$counter ) { $tag = $matches[1]; $attrs = $matches[2]; $text = wp_strip_all_tags( $matches[3] ); $slug = sanitize_title( $text ); // Make unique if ( isset( $counter[ $slug ] ) ) { $counter[ $slug ]++; $slug .= '-' . $counter[ $slug ]; } else { $counter[ $slug ] = 0; } $headings[] = array( 'level' => (int) substr( $tag, 1 ), 'id' => $slug, 'text' => $text, ); return "<{$tag}{$attrs} id=\"{$slug}\">{$matches[3]}{$tag}>"; }, $content ); if ( empty( $headings ) || count( $headings ) < 2 ) { return array( 'content' => $content, 'toc' => '' ); } // Build TOC HTML $toc = '