How to Show Only the First Few Items in the Kadence Table of Contents Block

The Kadence Table of Contents block is a fantastic tool for improving navigation within your WordPress posts. However, by default, it displays all headings found in the content, which can be overwhelming for long-form articles.

If you want to display only the first three items in the Kadence TOC block while still keeping the rest accessible, you can achieve this using CSS and JavaScript. This guide will walk you through the process step by step.

Step 1: Hide Extra TOC Items with CSS

First, let’s apply some CSS to hide all TOC list items beyond the first three. Add the following CSS to your WordPress Custom CSS area (Appearance > Customize > Additional CSS):

.wp-block-kadence-tableofcontents ul li:nth-child(n+4) {
    display: none;
}

Explanation:

  • nth-child(n+4): Selects all list items starting from the fourth one.
  • display: none;: Hides these elements from view.

This will initially hide everything beyond the first three items in the Table of Contents.

Step 2: Add a “Show More” Button with JavaScript

To make the hidden items accessible, we can use JavaScript to toggle their visibility when a user clicks a Show More button.

Navigate to Appearance > Theme File Editor and add the following JavaScript to your theme’s custom scripts section (or use a plugin like Code Snippets to add it safely):

document.addEventListener("DOMContentLoaded", function() {
    let tocList = document.querySelector(".wp-block-kadence-tableofcontents ul");
    let hiddenItems = tocList.querySelectorAll("li:nth-child(n+4)");
    
    if (hiddenItems.length > 0) {
        let showMoreButton = document.createElement("button");
        showMoreButton.innerText = "Show More";
        showMoreButton.style.display = "block";
        showMoreButton.style.marginTop = "10px";
        
        showMoreButton.addEventListener("click", function() {
            hiddenItems.forEach(item => item.style.display = "list-item");
            showMoreButton.style.display = "none";
        });
        
        tocList.appendChild(showMoreButton);
    }
});

Explanation:

  • The script selects all TOC list items beyond the first three.
  • It creates a ‘Show More’ button and appends it to the TOC list.
  • When clicked, the hidden items become visible, and the button disappears.

Step 3: Test Your Changes

  1. Refresh your WordPress post containing the Kadence TOC block.
  2. Verify that only the first three headings are initially visible.
  3. Click the Show More button to reveal the remaining items.

Final Thoughts

By using a combination of CSS and JavaScript, you can limit the number of displayed TOC items while keeping the full list accessible with a simple toggle. This technique helps streamline your page design, improve readability, and offer a better user experience.

Similar Posts