Press ESC to close

Table of Contents

Automatic Table of Contents in WordPress Website without plugin

Automatic Table of Contents in WordPress Website without plugin

Let’s ditch bulky plugins and create a beautiful, easy-to-use table of contents (TOC) for your WordPress site. Say farewell to cumbersome plugins and embrace the freedom to design and navigate effortlessly. Our method ensures your TOC smoothly directs readers on any device, without weighing down your site. You’ll have full control to match its style to your website perfectly. Ready to impress your audience with seamless browsing? Let’s dive in!

Important of Table of Contents in Website.

In WordPress, a Table of Contents (TOC) serves as a roadmap, listing the main headings or topics covered within a lengthy page or post. Usually positioned at the start, it enables readers to swiftly navigate to particular sections they find relevant or intriguing.

Enhanced user experience: Simplifies the process for readers to locate desired information, particularly on lengthier pages.
Boosted engagement: Motivates readers to delve into various sections of your content.
Improved SEO: Assists search engines in comprehending your content’s structure more effectively, potentially enhancing your ranking.

How we make table of contents in WordPress Websites?

Let’s forget about using ready-made plugins! Instead, we’ll create our own table of contents (TOC) from scratch using PHP, CSS, and JavaScript. This way has lots of benefits:

Custom Design: Get creative! Instead of using a generic plugin look, we can design a TOC that fits perfectly with the style and branding of our website. Think about matching fonts, colors, and layouts for a really unified look.

Faster Performance: No more slow-downs from bulky plugins. By building our own TOC, we only include the features we really need, which keeps our website quick and snappy.

Flexibility: We can make the TOC work exactly how we want it to. Want to include certain headings or leave some out? We can also decide how many levels of headings to show, and even add cool stuff like smooth scrolling or collapsible sections.

FeaturePluginCustom Code
DesignLimited optionsFully customization
PerformanceCan slow down siteLightweight and efficient
FlexibilityFixed featuresAdaptable to specific needs
Advance FeaturesRestrictedWide range of possibilities
Understanding the Advantage

Features of Our Table of Contents.

Certainly! Here are some of the features of the custom table of contents coding we implemented:

  • Dynamic Generation: The table of contents is generated dynamically based on the headings within the post content, ensuring that it automatically updates as the content changes.
  • Customization: Users can customize the appearance of the table of contents, including its position, styling, and animation effects, to match their website’s design.
  • Responsive Design: The table of contents is designed to be responsive, ensuring optimal display and functionality across various devices and screen sizes.
  • Smooth Animation: An animation effect is applied to the table of contents container to create a smooth transition when it appears or disappears.
  • Hyperlinks: Each table of contents item is hyperlinked to its respective heading within the post content, allowing users to navigate directly to specific sections.
  • Close Button: A close button is provided within the table of contents container to allow users to easily hide it when not needed.
  • Styling Options: The table of contents items, post title, and close button can be styled using CSS to match the website’s design preferences.
  • User Interaction: Users can interact with the table of contents by clicking on the button to reveal it, clicking on table of contents items to navigate, and clicking on the close button to hide it.
  • Automatic Display on Posts: The table of contents is designed to automatically appear on single post pages, eliminating the need for manual insertion. This feature streamlines the user experience by dynamically presenting the table of contents when viewing lengthy posts.
  • Positioning: The table of contents is positioned in the middle left side of the website, ensuring optimal visibility and accessibility for users.
  • Responsiveness: The table of contents is fully responsive and adjusts seamlessly to different screen sizes, ensuring optimal display and functionality on both mobile and desktop devices.
  • Lightweight: Our custom table of contents solution is lightweight and optimized for performance, ensuring minimal impact on website loading times. Unlike plugins that may introduce unnecessary bloat and slow down your website, our solution is designed to be efficient and streamlined, providing a seamless user experience without compromising speed.

Read also, How to add sticky Social Media bar in WordPress Websites / What is meta tags and how to add on WordPress Websites

First Step, Adding PHP on Header.PHP

  1. Log in to your WordPress dashboard.
  2. Navigate to “Appearance” > ” Theme File Editor”.
  3. In the Theme File Editor, single.php for post-specific functionality. If you want to show table of contents button every ware in your website open functions.php .
  4. Copy the given PHP code and past on single.php or if you want to show table of content every ware of you website past code in functions.php.
<?php
// Other PHP code for fetching header, footer, etc.

// Start of the loop
while (have_posts()) : the_post();

// Place the PHP code here
if (is_single()) : ?>
    <div id="toc-button">Table of Contents</div>
    <div id="toc-container">
        <button id="close-toc">Close</button>
        <h1><?php the_title(); ?></h1>
        <ul>
            <?php 
                // Code to generate table of contents dynamically based on headings in the post
                $content = get_the_content();
                $pattern = '/<h([2-6]).*?>(.*?)<\/h\1>/';
                preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);
                foreach ($matches as $match) {
                    $heading_level = $match[1];
                    $heading_text = $match[2];
                    $heading_slug = sanitize_title($heading_text);
                    echo '<li><a href="#toc-heading-' . $heading_slug . '">' . $heading_text . '</a></li>';
                    // Replace the original heading with the heading containing the anchor link
                    $content = str_replace($match[0], '<h' . $heading_level . ' id="toc-heading-' . $heading_slug . '">' . $heading_text . '</h' . $heading_level . '>', $content);
                }
            ?>
        </ul>
    </div>
<?php endif; ?>

<!-- The rest of your single post template code goes here -->

<?php endwhile; ?>
  1. Past the code here is a sample where you have to past code. I am placing this code on single.php because I want to show Table of Content only on post.
  1. After placing the code click on update.

Here, We done first step of adding table of content on WordPress website let’s do second steps.

Second Step, Adding CSS Code.

  1. From the WordPress dashboard, go to “Appearance” > “Customize”.
  2. In the Customizer, look for the “Additional CSS” option.
  3. Copy the given CSS code.
#toc-button {
  position: fixed;
  top: 50%;
  left: -40px; /* Adjust as needed */
  transform: translateY(-50%) rotate(-90deg); /* Rotate label vertically */
  background-color: #fff;
  border: 1px solid #ccc;
  padding: 5px 10px;
  cursor: pointer;
  z-index: 9999;
  transition: left 0.3s ease; /* Smooth transition when appearing from left */
  border-radius: 20px; /* Squircle shape */
  font-family: "italic", sans-serif; /* Change the font family as needed */
  /* Other styling properties for the button */
}

#toc-container {
  position: fixed;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
  background-color: #f0f0f0; /* Light gray color for the container */
  border: 1px solid #ccc;
  padding: 10px;
  display: none;
  z-index: 9999;
  width: 300px; /* Adjust the width as needed */
  border-radius: 20px; /* Apply squircles border-radius */
}

#toc-container ul {
  list-style-type: none; /* Remove default bullets */
  padding: 0;
  margin: 0; /* Add margin to control the list position */
}

#toc-container ul li {
   color: #333; /* Change the font color as needed */
	font-style: italic; /* Set the font style of the table of contents item to italic */
  margin-bottom: 5px;
  padding-left: 20px; /* Add padding to accommodate the bullets */
  position: relative; /* Make the li items relatively positioned */
}

#toc-container ul li::before {
  content: '\2022'; /* Add bullet character */
  position: absolute;
  left: 0;
}


#close-toc {
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: transparent;
  border: none;
  cursor: pointer;
}

#toc-container h1 {
  font-style: italic; /* Set the font style of the post title to italic */
  font-size: 16px; /* Adjust the font size as needed */
  margin-bottom: 10px; /* Add some bottom margin for separation */
  color: #333; /* Change the font color as needed */
}
  1. Paste your CSS code into the text area provided. Write your CSS rules within <style> tags.
  2. Click the “Publish” button to save your CSS changes.

Here, We done second step of adding table of content on WordPress website let’s do third steps.

Third Step, Adding Java Script Code.

If you have a separate JavaScript file for your theme, locate and open it in the Theme Editor. If not, you can create a new file. Paste your JavaScript code directly into the file. Make sure to follow proper JavaScript syntax. Once you’ve added the JavaScript code, click the “Update File” button to save your changes. How to add JavaScript without plugins on WordPress Websites. If you have problem with this steps you can do on another way here is a steps.

  1. Log in to your WordPress dashboard. Navigate to “Plugins” > “Add New”. Search for “WPCode Light”. Click “Install Now” and then “Activate” to activate the plugin.
  2. Click on />Code Snippet > +Add Snippet > Add Your Custom Code (New Snippet)
  1. Choose code type JavaScript Snippet Paste given code on box.
jQuery(document).ready(function($) {
  $('#toc-button').click(function() {
    $(this).fadeOut('slow'); // Hide the table of contents button
    $('#toc-container').css({'display': 'block', 'left': '-300px', 'opacity': 0}).animate({left: '10px', opacity: 1}, 'slow'); // Show and animate the table of contents container from the left with opacity animation
  });

  // Hide the table of contents box when clicking on other areas of the website
  $(document).on('click', function(event) {
    if (!$(event.target).closest('#toc-button, #toc-container').length) {
      $('#toc-container').hide();
      $('#toc-button').fadeIn('slow'); // Show the table of contents button
    }
  });

  // Close the table of contents box when clicking on the close button
  $('#close-toc').click(function() {
    $('#toc-container').hide();
    $('#toc-button').fadeIn('slow'); // Show the table of contents button
  });

  // Hide the table of contents box and show the button when clicking on a table of contents item
  $('#toc-container a').click(function() {
    $('#toc-container').hide();
    $('#toc-button').fadeIn('slow'); // Show the table of contents button
  });
});
  1. Click on Save Snippet and click on Inactive button to active JavaScript.

Here, We done third step of adding table of content on WordPress website let’s do forth steps.

Fourth Step, Adding HTML Anchor.

This steps is little understanding read the steps very carefully apply.

  1. After adding PHP, CSS and JavaScript.
  2. Open the post in new tab. There you will see now table of contents button middle left side of your website.
  1. Click on table of content button then Another box will appear there with table of content item list.
  2. When you click on the list item. On top of website link bar there will be change link like: “#toc-heading-” will added automatically. You can see on picture given below.
  1. Copy the link from toc-heading to end example: If link is “www.nbtechpro.com/how-to-add-table-of-contents/#toc-heading-what-is-table-of-contents” . Do copy toc-heading-what-is-table-of-contents .
  2. After Copy the Toc Heading link go to Post > Edit and click on the Heading > block > Advance > HTML ANCHOR Paste TOC Heading link here.
  1. Do same process on each heading. And add HTML anchor on each heading.

Note: When you do copy paste the Toc-heading. After copy the link past on correct heading HTML Anchor. Follow steps for each heading.

Important Notes:

  • Backup Your Website: Before making any modifications to your theme files or adding custom code, it’s essential to backup your website to prevent data loss in case of any unforeseen issues.
  • Theme Compatibility: While our custom table of contents solution is designed to be compatible with most WordPress themes, it’s recommended to test it on a staging site or a local development environment to ensure compatibility with your specific theme.
  • Code Placement: Ensure that you insert the PHP, CSS, and JavaScript code snippets in the correct locations within your theme files. Incorrect placement may result in errors or unexpected behavior.
  • Customization: Feel free to customize the CSS styles and JavaScript functionality to match your website’s design and requirements. You can adjust colors, fonts, positioning, and animation effects to create a unique table of contents experience.
  • Testing: After implementing the custom code, thoroughly test the table of contents functionality across different devices and screen sizes to ensure proper display and functionality.
  • Performance Optimization: While our custom solution is lightweight and optimized for performance, it’s advisable to monitor your website’s speed and performance after implementation. Consider using caching plugins and other optimization techniques to maintain optimal performance.

Guide Video

Wrapping Up:

Adding a “table of contents” to your WordPress website is like adding a map to your writing. It helps people find what they’re looking for quickly and easily, making it more enjoyable to read your longer articles and posts.

Our special table of contents tool does this automatically, based on the headings you already have in your writing. You can even adjust its appearance to match your website’s style and add cool animations if you want. Plus, it won’t slow down your website, unlike some other tools.

Whether you’re a writer, content creator, or business owner, this tool can help you organize your website and keep your readers engaged. Make your website easier to use and capture your audience’s attention with our user-friendly and fast table of contents feature.

Leave a Reply

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