When I write longer articles here on Kolakube, I like to add a Table of Contents to the top to help my reader’s navigate to different sections of the post.
Check out the latest issue in Build With MD to see it in action →
Lately a lot of you have been asking how I did it, so this post is my quick explanation showing how (of course, I’ll be referencing to Marketers Delight as that’s the theme I use here).
Step 1: Install Table of Contents Plus
I usually like to build features like this myself, but when I found Table of Contents Plus I knew it would just be a waste of time because this plugin nails it.
It’s a free plugin from the WordPress repository, so search for “Table of Contents Plus” from the Plugins screen in your Dashboard to find it.
Once you install it, go ahead and activate it.
Step 2: Configure Some Settings
This plugin comes with a very detailed options panel. These options do more than I need, but the author made it very easy to turn different settings on/off.
Here’s a screenshot of the settings I configured below. You may make tweaks based on your own preferences and the theme you’re using on your site.
Again, I made these decisions based on my own preferences and the fact that Marketers Delight takes care of most of the styling.
Also, I prefer to manually insert the Table of Contents into my posts rather than the plugin adding it to every post/page. I’ll show you that in the next step.
Click for a larger view.
3. Step 3: Add the Shortcode to Your Posts
The final step to adding a table of contents to your posts is to insert the shortcode the plugin provides.
I like to put it at the very beginning, so before any text in the post editor I place the
toc shortcode. Nothing to it.
Step 4: Styling Table of Contents in MD
Add this CSS to your Child Theme’s
style.css file to add a background color and some spacing:
You may also position it to the edge of your content box by wrapping the shortcode in your post editor with this little bit of HTML:
<div class="alignright wrap">[toc]</div>
Bonus: Optimize the Scripts + Styles this Plugin Loads
As a developer, I know too much. I know that the scripts and styles this plugin loads on every page of your site won’t be necessary when you don’t have a table of contents on the page. Extra HTTP requests can slow your page down, so I remove them when I can.
I came up with a little function that will load the resources needed for this plugin *only* when you have the
[toc] shortcode in your post editor. If not, nothing will load.
Go ahead and paste this function into your Child Theme’s
functions.php file (see this for guidance):
Let me know if you have any issues with this, I’ll do my best to help you out.