目次
はじめに
WordPress(SWELLテーマ)では、投稿ページや固定ページにH2/H3があると、テーマ側で自動的に目次が生成される仕様になっています。しかし、ブログパーツは目次が自動表示されないため、自前で目次を出力したくなる場面があります。
本記事では、H2/H3を元に目次を自動生成する [custom_toc]
というショートコードを実装し、SWELLの自動目次機能と競合せず共存可能な構成で記録します。
PHPコード(functions.phpに追加)
// [custom_toc] - 見出しから目次を生成するショートコード
function custom_toc_shortcode($atts) {
$content = apply_filters('the_content', get_the_content());
$matches = [];
preg_match_all('/<h([23])[^>]*>(.*?)<\/h[23]>/', $content, $matches, PREG_OFFSET_CAPTURE);
if (empty($matches[0])) return '';
$toc = '<div class="swell-toc-box"><strong>目次</strong><ul>';
$offset = 0;
foreach ($matches[0] as $index => $match) {
$level = $matches[1][$index][0];
$title = strip_tags($matches[2][$index][0]);
$id = 'heading-' . $index;
$anchor = '<a id="' . $id . '"></a>';
$pos = $match[1] + $offset;
$content = substr_replace($content, $anchor . $match[0], $pos, strlen($match[0]));
$offset += strlen($anchor);
$toc .= '<li class="swell-toc-level-' . $level . '"><a href="#' . $id . '">' . $title . '</a></li>';
}
$toc .= '</ul></div>';
return $toc . $content;
}
add_shortcode('custom_toc', 'custom_toc_shortcode');
CSSコード(style.cssに追加)
/* ページパーツ目次用([custom_toc]) */
.swell-toc-box {
border: 1px solid #ddd;
background: #f7f7f7;
padding: 1.2em;
margin-bottom: 2em;
font-size: 0.95em;
}
.swell-toc-box ul {
list-style: none;
padding-left: 0;
margin: 0;
}
.swell-toc-box li {
margin: 0.4em 0;
}
.swell-toc-level-2 {
margin-left: 0;
font-weight: bold;
}
.swell-toc-level-3 {
margin-left: 1.5em;
font-weight: normal;
font-size: 0.95em;
}
記事には下のショートコードを追加するだけでOK
[custom_toc]
機能概要と注意点
項目 | 内容 |
---|---|
目的 | ブログパーツ用に目次を個別出力 |
対象 | H2/H3の見出し構造を元にリンク付き目次を生成 |
注意点 | 投稿ページや固定ページでしようするとショートコード目次を優先してしまう |
使い方
- PHPコードを
functions.php
に追加(子テーマ推奨) - CSSコードを
style.css
に追加 - ブログパーツに
[custom_toc]
を記述 - H2/H3 を含む構造文がある場合、自動的に目次が表示される
まとめ
SWELLでは投稿や固定ページにおいて目次が自動生成される一方、ブログパーツや再利用ブロックではそれが無効です。本記事で紹介した [custom_toc]
ショートコードは、ブログパーツに埋め込んだh2,h3ブロックを見出しにすることができる。