Automatic Table of Content for Your WordPress Posts, Conditional Auto Insert before the First H2
WPCodeBox
Creating a Conditional Table of Contents for WordPress Posts. When enhancing the readability of long-form content, including a Table of Contents (TOC) is beneficial for your readers. On WordPress, you can automatically generate and insert a TOC for single post-entries that have structural headings (<h2> and <h3>) using the DOM Document class. However, to avoid clutter and maintain relevance, showing the TOC only when there are enough headings is prudent. Here, we'll demonstrate how to achieve this by showing the TOC only if there are more than two <h2> elements in your post content.
Additional Snippets
Add it to WPCodebox or in your functions.php
View on GitHub