Table of Contents:
- Installing the WPCode Plugin
- How to Create a Table of Contents in WordPress Using a Snippet
- How the Snippet Works
- Filtering Post Content:
- Condition Checks:
- Working with the DOM:
- Creating the TOC:
- Final Output:
- Why Is a Table of Contents Good for SEO?
- Conclusion
Last updated February 11th, 2025 13:01
A Table of Contents (TOC) is a list of links that displays the main headings or sections of an article. It is typically placed at the beginning of a post, allowing readers to quickly navigate to the section they are interested in. Some page builders, such as Elementor or SeedProd, offer this feature through a built-in widget. However, if you are using the default Gutenberg editor, adding a TOC manually can be challenging.
In this guide, we’ll show you how to use a custom snippet to automatically generate and insert a Table of Contents at the beginning of your articles. This snippet is designed to detect headings (<h2> and <h3>) and create a TOC dynamically. To implement this solution, you only need one powerful and versatile plugin — WPCode.
Installing the WPCode Plugin
To insert custom code into your WordPress site, you have two options:
- Manually add the code to the appropriate file.
- Use a plugin that dynamically injects the code while the site runs.
The second option is safer because it prevents your code from being lost after a theme or plugin update.
Follow these steps to install WPCode:
- In the WordPress dashboard, go to Plugins → Add New.
- Use the search bar in the top right corner and type WPCode.
- Once you find the plugin, install and activate it.
If you want a complete guide on how to use this plugin, check out: How to Insert Custom Code in WordPress.
How to Create a Table of Contents in WordPress Using a Snippet
You now have the WP Code plugin installed, and a new item “Code Snippets” has been added to the left menu. Click on it and select “+ Add Snippet” from the menu. On the next screen, click on “Add Your Custom Code (New Snippet)”. First, enter a custom name for the snippet and then select the code language. The snippet is written in PHP.
Insert the following piece of PHP code into the code editor:
add_filter( 'the_content', function ( $content ) {
// This snippet requires the DOMDocument class to be available.
if ( ! class_exists( 'DOMDocument' ) ) {
return $content;
}
if ( !is_single() || !in_the_loop() || !is_main_query() ) {
return $content;
}
$dom = new DOMDocument();
$load_content = mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' );
if ( empty( $load_content ) ) {
return $content;
}
@$dom->loadHTML( $load_content );
$xpath = new DOMXPath( $dom );
$headings = $xpath->query( '//h2 | //h3' );
// Let's loop through all the headings and add them to the table of contents.
$headings_list = ' ';
foreach ( $headings as $heading ) {
$heading_id = $heading->getAttribute( 'id' );
if ( empty( $heading_id ) ) {
// Generate a heading id and add it to the heading.
$old_heading = $heading->C14N();
$heading_id = sanitize_title( $heading->nodeValue );
$heading->setAttribute( 'id', $heading_id );
$content = str_replace( $old_heading, $heading->C14N(), $content );
}
$heading_text = $heading->nodeValue;
$headings_list .= '- ' . $heading_text . '
';
}
$headings_list .= '
';
$content = $headings_list . $content;
return $content;
} );
How the Snippet Works
Filtering Post Content:
The snippet hooks into the the_content filter, modifying the post content before it is displayed on the front end.
Condition Checks:
The TOC is generated only if:
- The post is a single post page (is_single()).
- The post is in the main query (is_main_query() and in_the_loop()).
Working with the DOM:
- Uses DOMDocument to parse the post’s HTML and locate and headings via XPath.
- If a heading does not have an ID, one is automatically generated (e.g., from the heading text).
Creating the TOC:
- Generates an HTML unordered list () with anchor links ().
- This list is inserted at the beginning of the post content.
Final Output:
When the post is displayed, a Table of Contents is automatically added at the top if the post contains or headings.
Why Is a Table of Contents Good for SEO?
A Table of Contents (TOC) benefits SEO for several reasons, improving both user experience and search engine optimization:
- Improves Content Structure – TOC helps search engines (such as Google) better understand the structure of an article. When content is well-organized and divided into clear sections, search engines can index individual parts more effectively and provide relevant results for different queries.
- Increases Click-Through Rate (CTR) – If TOC appears in sitelinks (i.e., the structured links displayed in search results), it can significantly improve CTR. When users see that a page has well-structured content with direct links to different sections, they are more likely to click.
Reduces Bounce Rate – When users quickly find the relevant section thanks to TOC, they tend to spend more time on the page. A lower bounce rate signals to search engines that the page contains valuable content.
Enhances User Experience (UX) – TOC simplifies navigation, especially for long-form articles. When users can easily find the information they need, they are more satisfied, which contributes to a positive user experience—a factor Google increasingly values when ranking pages.
Quick Access to Key Information – TOC ensures that both readers and search engines can quickly access the main topics of an article. This allows search engines to better match articles with relevant queries, improving their visibility in search results.
Increases Chances of Featured Snippets – A well-structured TOC with relevant headings can increase the chances of appearing in Featured Snippets (highlighted answer boxes in search results). TOC helps search engines identify key points that are relevant to specific queries.
Supports Mobile Users – An interactive TOC with clickable links makes it easier for mobile users to navigate content without excessive scrolling, improving their overall experience.
Semantic Highlighting of Headings – TOC helps search engines differentiate between heading levels (H1, H2, H3) and understand how content is hierarchically structured. This improves content indexing and relevance assessment.
Conclusion
A Table of Contents has a positive impact on SEO by improving content structure, navigation, and user engagement. It ensures proper indexing by search engines, increasing the likelihood of appearing in sitelinks or featured snippets. A well-structured TOC can boost search rankings, leading to higher traffic and better SEO performance. With a simple code snippet, adding TOC is quick and easy.
The website is created with care for the included information. I strive to provide high-quality and useful content that helps or inspires others. If you are satisfied with my work and would like to support me, you can do so through simple options.
Byl pro Vás tento článek užitečný?
Klikni na počet hvězd pro hlasování.
Průměrné hodnocení. 0 / 5. Počet hlasování: 0
Zatím nehodnoceno! Buďte první
Je mi líto, že pro Vás nebyl článek užitečný.
Jak mohu vylepšit článek?
Řekněte mi, jak jej mohu zlepšit.
Subscribe to the Newsletter
Stay informed! Join our newsletter subscription and be the first to receive the latest information directly to your email inbox. Follow updates, exclusive events, and inspiring content, all delivered straight to your email.