Add Table of Contents without plugin in WordPress

Add Table of Contents without plugin in WordPress

To beat your competitors and make a better position in SERP (search engine result page), you must think about all the possible ways you can make your content more worthy to Google.  For this, SEO specialists suggest us to use a table of contents in WordPress posts. We will make a custom Table of contents without plugin today.

What is Table of Contents and Why should you use it?

A Table of Contents is nothing but an index that shows which topics are described and in what order in your article. Yes, as simple as you thought. Table of Contents is convenient for a reader as well as Google to read the article. Apart from that, sometimes, Google directly uses your Table of Contents in SERP for an appropriate search.

TOC in SERP
Table of contents in SERP

Why not use a Table of Contents plugin?

There is a lot of free Table of Contents plugins available in WordPress. Then why should you add a custom TOC (table of contents) in your blog instead of using a plugin? Let me answer this. You should not use a TOC plugin because-

  • Almost all of the Table of Contents plugins add extra CSS and JS files which requires more space in your server.
  • Most importantly, these CSS and JS files increase page loading time which has a bad impact on SEO.

How Page Speed Affects SEO & Google Rankings

Why use a custom Table of Contents?

  • No extra CSS or JS files, no extra space consumption.
  • Loading time is not increased (which makes Google happy)

How to make custom Table of Contents

Okay, enough talk. Now I will show you how to make your own custom Table of Contents. I will show the process step by step so you can understand easily. Note that, it requires basic coding knowledge. If you don’t know anything about coding, don’t worry. I’ll do it for you.

In two ways you can implement the code. One, by adding the code in theme’s function.php file. Two, by making a custom plugin.

Method 1: By theme function.php file

First, create a child theme for your current theme if you are not using any child theme. Because if you make any change/add any code in your current active theme, they will go away once you update the theme. If you don’t know about child theme and what it does, learn more about child theme. Or you can skip to next method. I have prepared all the necessary files for you there.

Now add the following code at the bottom of your child-theme function.php file.

 

//=====================================================================
// Table of contents shortcode
// Example: [ctoc title="Table Title" type="ul" items="Item1,Item 2"]
//=====================================================================

function custom_toc_shortcode_devslib( $atts ) {
	// defaults
	$a = shortcode_atts( array(
		'title' => 'Table of contents',
		'type' => 'ol',
		'items' => ''
	), $atts );
	$r = '<div class="toc"><h4>'.$a['title'].'</h4><'.$a['type'].'>';

	if(!empty($a['items'])){
		$items = explode(",", $a['items']);
		foreach($items as $item){
			$r .= '<li><a href="#'.str_replace(' ', '_', $item).'">'.$item.'</a></li>';
		}
	}
	
	$r .= '</'.$a['type'].'></div>';
	return $r;
}

add_shortcode( 'ctoc', 'custom_toc_shortcode_devslib' );

//===========================================================================
// Function to add ID to every heading tag if [ctoc] shortcode is used
// `<h2>Hello there</h2>` converts to `<h2 id="Hello_there">Hello there</h2>`
//===========================================================================


function auto_id_headings_devslib( $content ) {
	
	if(has_shortcode( $content, 'ctoc' )){
		$content = preg_replace_callback( '/(\<h[1-6](.*?))\>(.*)(<\/h[1-6]>)/i', function( $matches ) {
			if ( ! stripos( $matches[0], 'id=' ) ) :
				$matches[0] = $matches[1] . $matches[2] . ' id="' . str_replace(' ', '_', $matches[3]) . '">' . $matches[3] . $matches[4];
			endif;
			return $matches[0];
		}, $content );
	}
	
    return $content;
}
add_filter( 'the_content', 'auto_id_headings_devslib' );

//==========================================================
// ADD CSS CODES IN WP_HEAD
//==========================================================

function css_for_custom_toc_devslib() {
    ?>
<style>
.toc{float:right;max-width:40%;min-width:35%;padding:10px 0 0 10px;border:1px solid #ccc;margin:0 0 10px 10px}.toc h4{margin-bottom:10px}.toc ul,.toc ol{margin:10px 10px 10px 20px}@media only screen and (max-width:959px){.toc{width:100%;max-width:unset;min-width:unset;float:none;padding:10px;margin:unset}}</style>
    <?php
}
add_action('wp_head', 'css_for_custom_toc_devslib');

I’ll explain the code later. If you added the code, it’s done. Skip to How this works section. Or continue to method 2.

Method 2: Custom TOC plugin

Before I said, we will add Table of Contents without plugin. Yes, we do not require any plugin for this job. But if you don’t want to touch any code, I have prepared a custom plugin that you can simply install. After installing, activate the plugin and start using it. This plugin is very light-weight (only 2.42Kb) and cannot be compared with other available plugins.

  1. First, download the plugin from GitHub. (You can see the code used in the plugin here.)
  2. Then go to your WordPress dashboard > Plugins > Add new > Upload plugin
  3. Upload the downloaded ZIP (custom-table-of-contents-1.0.zip) file
  4. After uploading, activate the plugin.
  5. Done.

How this works

I have commented on all the codes used here. The first function custom_toc_shortcode_devslib() creates a shortcode that accepts some parameters. The second function auto_id_headings_devslib() creates id attribute for every HTML heading tags for navigation and the third function css_for_custom_toc_devslib() adds some CSS codes to <head> of the HTML document used in the table.

How to add Table of Contents into posts

First, write your post as you write all the time. Then add the custom shortcode [ctoc title=”Table title” type=”ol” items=”Heading 1,Heading 2″] at the top of the post.

Accepted parameters

  • title = Title of the table
  • type = ol for ordered list, ul for unordered list
  • items = headings you want to add to the table (Copy all the headings as they are in the post and separate with a comma only [don’t use any extra space]. See the example below for better understanding.)

Example

[ctoc title="Table of contents" type="ol" items="What is Table of Contents and Why should you use it?,Why not use a Table of Contents plugin?,Why use a custom Table of Contents?,How to make custom Table of Contents,Method 1 - By theme function.php file,Method 2 - Custom TOC plugin,How this works,How to add Table of Contents into posts,Pros of custom Table of Contents Plugin,Cons of custom Table of Contents Plugin"]
This shortcode creates a table like this. (Yes, I am also using the same plugin)

custom Table of Contents example
custom Table of Contents example

Pros of custom Table of Contents Plugin

  • Easy to implement
  • Very light-weight (only 2.42Kb)
  • Very fast, does not affect page speed

Cons of custom Table of Contents Plugin

  • Not automatic, you need to use shortcode
  • You cannot add any sub-item to the table.

This is it. Hope you understood the process. If you have any questions or suggestions about anything, please write it on the comment. I will happy to read your comments!

Thank you.

David Moss

Developer | Writer | Coffee lover

Leave a Reply