KH-WEBLOG TOP > WEBメモ > WordPress > TOCで最初は目次の小見出しを非表示で開閉ボタンでアコーディオン表示する方法:WordPress

TOCで最初は目次の小見出しを非表示で開閉ボタンでアコーディオン表示する方法:WordPress

WordPressのTOC(Table of Contents Plus)プラグインの見出しで、
最初は目次の小見出しを非表示で開閉ボタンでアコーディオン表示する方法をご紹介します。

※デモはこのサイトのこのページの目次で確認してください。

コーディング・WordPress化作業を代行します

TOCの設定

まずはTOCの設定画面の
「ユーザーによる目次の表示・非表示を切り替えを許可」
の項目のチェックを外します。

cssの設定

cssに下記のコードを追加します。

CSSのコード


#toc_container .toc_list li ul {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.4s ease;
}

/* 表示状態(開いたとき) */
#toc_container.show-children .toc_list li ul {
  max-height: 1000px; /* 十分大きな値を指定 */
}

/* トグルボタンのスタイル */
#toc-toggle-all {
  cursor: pointer;
  font-size: 0.9em;
  background: none;
  border: none;
  color: #0073aa;
  text-decoration: underline;
  margin-top: 5px;
}

javascriptの設定

下記のjsをフッターかjsファイルに追加します。

javascriptのコード

<script>
document.addEventListener("DOMContentLoaded", function () {
  const tocContainer = document.getElementById("toc_container");

  // 開閉ボタン作成
  const toggleBtn = document.createElement("button");
  toggleBtn.id = "toc-toggle-all";
  toggleBtn.textContent = "[開く]";

  // タイトル要素にボタンを追加
  const heading = tocContainer.querySelector("p.toc_title");
  if (heading) {
    heading.appendChild(toggleBtn);
  }

  // 開閉切り替え
  toggleBtn.addEventListener("click", function () {
    tocContainer.classList.toggle("show-children");
    const isOpen = tocContainer.classList.contains("show-children");
    toggleBtn.textContent = isOpen ? "[閉じる]" : "[開く]";
  });
});
</script>

以上で完成です。

細かい調整は各CSSやJSの該当部分を変更する事で可能です。

コーディング・WordPress化作業を代行します

WordPressのおすすめ参考書

楽天Kobo電子書籍ストア
¥3,278 (2025/07/08 15:26時点 | 楽天市場調べ)

TAGS

.htaccess ActionScript All in one seo pack Contact Form 7 CSS CSS3 EC-CUBE Flash HTML HTML5 JavaScript jQuery LightBox PHP RSS SEO WordPress アイキャッチ画像 アクセス解析 カスタムフィールド カテゴリー カラーミーショップ カート コメント ショートコード テンプレートタグ ドロップダウンメニュー パーマリンク フォーム フルスクリーン ブログカード プラグイン ページテンプレート ページナビ ページ分割 マウスイベント リダイレクト リンク リンクカード レンタルサーバー ロールオーバー 携帯サイト 条件分岐 正規表現 関連記事