A table of contents is a great way to enhance your site’s navigation and SEO. In this post, you will discover how to create a table of contents for a single post or for all your WordPress posts at once.

Create table of contents in WordPress

In this post, you will discover various methods to create a table of contents in WordPress.
Let’s dive in!

Create table of contents in WordPress by Kadence plugin

Step 1: Install Kadence Blocks:

Kadence Blocks is the most popular Gutenberg plugin that extends the functionality of Gutenberg and gives you access to a handful of extra Gutenberg blocks.
To install the Kadence Blocks plugin in WordPress, navigate to the Plugins section of your WordPress dashboard, click Add New, search for Kadence Blocks, select it from the results, and click Install Now.

Step 2: Add Kadence Table of Contents Block in WordPress

Now that you have Kadence Blocks installed and activated, it’s time to add a Table of Contents block to WordPress.

Click on the + button and then search for “Table of Contents” and choose the appropriate block.

table of contents block in Kadence blocks

As soon as you add the Table of Contents block to your post, you will see the title “Table of Contents” along with a message saying “Start adding Heading blocks to create a table of contents.” if your post doesn’t have any headings yet.

However, one of the best features of the Kadence Table of Contents block is that it automatically reads in your post headings and adds them to the Table of Contents without you having to do anything.

Create table of contents in WordPress Without plugin

In this method, we will define a shortcode in WordPress using a piece of code, and then we will add the table of contents to our posts using this shortcode.

Step 1: Add The Following Code to the functions.php File

In the WordPress dashboard, go to Appearance ➡ Theme File Editor and copy the following code into the theme’s functions.php file and update it.

You must create a child theme before making any changes to functions.php file. Otherwise, the applied changes will be lost after each update.
Create child theme in WordPress step by step [without plugin]

As an alternative method, you can use the Code Snippets plugin to insert your codes into WordPress.


/*
* [table_of_contents]
* @update: https://redpishi.com/wordpress-tutorials/table-of-contents-in-wordpress/
*/

      
add_action( 'the_content', function($content){
	
	/*****************************
	*	Choose where to display:
	*	0 = only shortcode
	*	1 = all posts
	*****************************/	
	$table_of_contents_type = 0; 	
	


	/*****************************
	*	Exclude posts
	*	[1,2,post_id]
	*****************************/	
	$Excluded_posts=[-1];




	/*****************************
	*	Exclude categories
	*	[10,20,cat_id]
	*****************************/	
	$Excluded_categories=[-1];	



	
    if (strpos( $content, '[table_of_contents]') !== false || ( $table_of_contents_type == 1 && !is_single($Excluded_posts) && !in_category($Excluded_categories) )  ) {
        $content = preg_replace_callback( '/(\<h[2-6](.*?))\>(.*)(<\/h[2-6]>)/i', function( $matches ) {
            if ( ! stripos( $matches[0], 'id=' ) ) :
            $matches[0] = $matches[1] . $matches[2] . ' id="' . sanitize_title( $matches[3] ) . '">' . $matches[3] . $matches[4];
            endif;
            return $matches[0];
        }, $content );
        

        $style = '<style>html { scroll-behavior: smooth; scroll-padding-top: 5em; .table_of_contents a { text-decoration: none; }}</style>';
        if 	( $table_of_contents_type == 1 ) 
        {
			$content = generateIndex($content)['index'].$content;
		} else
		{
			$content = str_replace("[table_of_contents]",generateIndex($content)['index'],$content);
		}
        
        return $style.$content;
    } else return $content;
    
});

function generateIndex($html) {
	preg_match_all('/<h([2-6])*[^>]*>(.*?)<\/h[2-6]>/',$html,$matches);
	$index = "<div class='table_of_contents'><ul>";
	$prev = 2;
	foreach ($matches[0] as $i => $match){
		$curr = $matches[1][$i];
		$text = strip_tags($matches[2][$i]);
		$slug = sanitize_title($text);
		$anchor = '<span id="'.$slug.'">'.$text.'</span>';
		$html = str_replace($text,$anchor,$html);
		$prev <= $curr ?: $index .= str_repeat('</ul>',($prev - $curr));
		$prev >= $curr ?: $index .= "<ul>";
		$index .= '<li><a href="#'.$slug.'">'.$text.'</a></li>';
		$prev = $curr;
	}
	$index .= "</ul></div>";
return ["html" => $html, "index" => $index];	}	

After updating the functions.php file, the [table_of_content] shortcode will be activated for you.

Step 2: Add the table of contents Shortcode

Now you can add the following shortcode to your post to add a table of contents.

[table_of_contents]

You’re done, now publish the post and check your table of contents.

Add table of contents to all posts

By setting $table_of_contents_type to 1, you can show a table of contents for every post.

$table_of_contents_type = 1; 	

Hide the table of content for certain posts

You can specify the posts that you want to exclude from showing the table of content by writing their slugs or ID’s as an array in $Excluded_posts.

	/*****************************
	*	Exclude posts
	*	[1,2,post_id]
	*****************************/	
	$Excluded_posts=[6,7]

Hide the table of content for posts in certain categories

You can specify the categories that you want to exclude from showing the table of content for their posts by writing their ID or slug as an array in $Excluded_categories.

	/*****************************
	*	Exclude categories
	*	[10,20,cat_id]
	*****************************/	
	$Excluded_categories=[20,30];	

If this article is difficult for you to read in text, you can watch the video version below.

Share this post
Maya
Maya

Hi, my name is Maya and I’m a WordPress plugin developer. I created this website to share some of the helpful codes that I’ve used in my own projects.
If you’re looking for a custom plugin for your website, you can contact me by clicking on Hire a developer in the menu. I’d love to hear from you.

Articles: 56

3 Comments

  1. I am really grateful for the instructions from your website..

    Please help me how to make them appear automatically in articles, because I have many articles that cannot be displayed manually

Leave a Reply

Your email address will not be published. Required fields are marked *