TOCで最初は目次の小見出しを非表示で開閉ボタンでアコーディオン表示する方法:WordPress
WordPressのTOC(Table of Contents Plus)プラグインの見出しで、
最初は目次の小見出しを非表示で開閉ボタンでアコーディオン表示する方法をご紹介します。
※デモはこのサイトのこのページの目次で確認してください。
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のおすすめ参考書
bookfan 1号店 楽天市場店
¥3,300 (2026/01/20 15:42時点 | 楽天市場調べ)

