ワードプレス

ワードプレスにプラグインなしで目次を追加する方法

今回はワードプレスの記事でよく見かける「目次」の導入方法を紹介します。

導入にあたり、こちらの石鷹さんの記事を参考にさせて頂きました。さらにはコメント欄にて手厚いフォローも頂きました。改めてありがとうございました。

この記事は備忘録として当ブログの目次関連部分のコードを記録しておくものです。コピペと微調整をして、ぜひ導入してみて下さい。

ちなみに、このブログはWordPressの公式テーマ「Twenty Twelve」をベースにカスタマイズしています。他のテーマにも応用可能です。

それでは、さっそく説明していきます。

目次を導入するメリット

こういった記事への訪問者の多くは、「何か具体的な欲しい情報」を抱えていると言われています。例えば、「美味しいコーヒーの淹れ方」を知りたい人の場合を考えてみます。

美味しいコーヒーを淹れるためには「コーヒー豆」「水」「正しい器具の使い方」など様々なファクターがあります。この中の「コーヒー豆」ひとつをとっても「保管方法」「挽き具合」「分量」など、さらに分岐したファクターがあります。

「美味しいコーヒーの淹れ方」というタイトルのページを訪れた読者の多くは、多岐にわたるファクターの中のどれかは既に知っているはずです。「美味しいコーヒー豆と水は知っているけれど、正しいドリップの仕方が分からない」といった具合です。

つまり記事全てを読む必要はないということになります。

さらに言い換えれば、既知の情報を読む時間はある意味「無駄」になってしまいます。そういった無駄を省くという意味でも、目次を設置するほうがブログを訪れて下さる読者の方に親切ですよね。

さらに僕自身にもメリットがありました。目次を導入するようになって以降h2タグの見出しを見て、読みやすく分かりやすい文章構成を意識するようになりました。ライティングスキルを磨くという意味でも目次は有効な手段になりそうです。

function.phpに記述するコード

ほぼ元のコードそのままですが微調整加えています。バックアップを忘れずに取った上で、function.phpに下記コードを記述します。

class Toc_Shortcode {

	private $add_script = false;
	private $atts = array();

	public function __construct() {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_shortcode( 'toc', array( $this, 'shortcode_content' ) );
		add_action( 'wp_footer', array( $this, 'add_script' ) );
	}

	function enqueue_scripts() {
		if ( !wp_script_is( 'jquery', 'done' ) ) {
			wp_enqueue_script( 'jquery' );
		}
	}

	public function shortcode_content( $atts ) {
		$this->atts = shortcode_atts( array(
			'id' => '',
			'class' => 'toc',
			'title' => '<span class="icon-info"></span> CONTENTS ',
			'toggle' => 'true',
			'opentext' => 'open',
			'closetext' => 'close',
			'showcount' => 2,
			'depth' => 0,
			'toplevel' => 2,
			'targetclass' => 'entry-content',
			'offset' => '',
			'duration' => 'normal'
		), $atts );

		$content = get_the_content();

		$headers = array();
		preg_match_all( '/<([hH][1-6]).*?>(.*?)<\/[hH][1-6].*?>/u', $content, $headers );
		$header_count = count( $headers[0] );
		$counter = 0;
		$counters = array( 0, 0, 0, 0, 0, 0 );
		$current_depth = 0;
		$prev_depth = 0;
		$top_level = intval( $this->atts['toplevel'] );
		if ( $top_level < 1 ) $top_level = 1;
		if ( $top_level > 6 ) $top_level = 6;
		$this->atts['toplevel'] = $top_level;

		// 表示する階層数
		$max_depth = ( ( $this->atts['depth'] == 0 ) ? 6 : intval( $this->atts['depth'] ) );

		$toc_list = '';
		for ( $i = 0; $i < $header_count; $i++ ) {
			$depth = 0;
			switch ( strtolower( $headers[1][$i] ) ) {
				case 'h1': $depth = 1 - $top_level + 1; break;
				case 'h2': $depth = 2 - $top_level + 1; break;
				case 'h3': $depth = 3 - $top_level + 1; break;
				case 'h4': $depth = 4 - $top_level + 1; break;
				case 'h5': $depth = 5 - $top_level + 1; break;
				case 'h6': $depth = 6 - $top_level + 1; break;
			}
			if ( $depth >= 1 && $depth <= $max_depth ) {
				if ( $current_depth == $depth ) {
					$toc_list .= '</li>';
				}
				while ( $current_depth > $depth ) {
					$toc_list .= '</li></ul>';
					$current_depth--;
					$counters[$current_depth] = 0;
				}
				if ( $current_depth != $prev_depth ) {
					$toc_list .= '</li>';
				}
				if ( $current_depth < $depth ) {
					$toc_list .= '<ul' . ( ( $current_depth == 0 ) ? ' class="toc-list"' : '' ) . '>';
					$current_depth++;
				}
				$counters[$current_depth - 1]++;
				$number = $counters[0];
				for ( $j = 1; $j < $current_depth; $j++ ) {
					$number .= '.' . $counters[$j];
				}
				$counter++;
				$toc_list .= '<li><a href="#toc' . ($i + 1) . '"><span class="contentstable-number">' . $number . '</span> ' . $headers[2][$i] . '</a>';
				$prev_depth = $depth;
			}
		}
		while ( $current_depth >= 1 ) {
			$toc_list .= '</li></ul>';
			$current_depth--;
		}

		$html = '';
		if ( $counter >= $this->atts['showcount'] ) {
			$this->add_script = true;

			$toggle = '';
			if ( strtolower( $this->atts['toggle'] ) == 'true' ) {
				$toggle = ' <span class="toc-toggle">[<a class="internal" href="javascript:void(0);">' . $this->atts['closetext'] . '</a>]</span>';
			}

			$html .= '<div' . ( $this->atts['id'] != '' ? ' id="' . $this->atts['id'] . '"' : '' ) . ' class="' . $this->atts['class'] . '">';
			$html .= '<p class="toc-title">' . $this->atts['title'] . $toggle . '</p>';
			$html .= $toc_list;
			$html .= '</div>' . "\n";
		}

		return $html;
	}

	public function add_script() {
		if ( !$this->add_script ) {
			return false;
		}

		$class = $this->atts['class'];
		$offset = is_numeric( $this->atts['offset'] ) ? (int)$this->atts['offset'] : - 1;
		$duration = is_numeric( $this->atts['duration'] ) ? (int)$this->atts['duration'] : '"' . $this->atts['duration'] . '"';
		$targetclass = trim( $this->atts['targetclass'] );
		if ( $targetclass == '' ) {
			$targetclass = get_post_type();
		}
		$targetclass = ".$targetclass :header";
		$opentext = $this->atts['opentext'];
		$closetext = $this->atts['closetext'];
		?>
<script type="text/javascript">
(function ($) {
  var offset = <?php echo $offset; ?>;
  var idCounter = 0;
  $("<?php echo $targetclass; ?>").each(function () {
    idCounter++;
    this.id = "toc" + idCounter;
  });
  $(".<?php echo $class; ?> a[href^='#']").click(function () {
    var href = $(this).attr("href");
    var target = $(href === "#" || href === "" ? "html" : href);
    var h = (offset === -1 ? $("#wpadminbar").height() + $(".navbar-fixed-top").height() : offset);
    var position = target.offset().top - h - 4;
    $("html, body").animate({scrollTop: position}, <?php echo $duration; ?>, "swing");
    return false;
  });
  $(".toc-toggle a").click(function () {
    var tocList = $(".toc-list");
    if (tocList.is(":hidden")) {
      tocList.show();
      $(this).text("<?php echo $closetext; ?>");
    } else {
      tocList.hide();
      $(this).text("<?php echo $opentext; ?>");
    }
  });
})(jQuery);
</script>
		<?php
	}

}

new Toc_Shortcode();

これで基本形は完成です。

ちなみに22行目の

<span class="icon-info"></span>

の部分だけちょっとオリジナリティを加えています。ウェブフォント「IcoMoon」を導入してインフォメーションマークを表示させてみました。(ウェブフォント導入方法はこちら

当ブログの実際のCSSコード

あとは見た目をCSSで整えます。以下、実際に今も当ブログで使っているコードです。

/*--------------------------------------
 もくじ
--------------------------------------*/
.toc {
    width: auto;
    display: table;
    margin: 15px 0px 15px 0px;
    padding: 10px 10px 10px 10px;
    color: #333;
    word-break: break-all;
    word-wrap: break-word;
    border: #ccc double 1px;
    background-color: #f5f5f5;
}
.toc .toc-title {
    margin: 0;
    padding: 0;
    text-align: center;
    font-weight: bold;
}
.toc .toc-toggle {
    font-weight: normal;
    font-size: 90%;
    text-decoration:none;
}
.toc ul{
    list-style: none;
    margin-left:-25px;
}
.toc .toc-list {
    margin: 0;
    margin-left:-30px;
    padding: 0;
}

ショートコード記述し目次を表示させる

次に目次を表示させたい場所に次のショートコードを記述します。

[toc]

これでうまく表示されているはずです。

こんな感じです。この画像では、h2,h3の2階層のみ表示させていますが、ショートコード内に記述を加えることで、さらにお好みのカスタマイズができるようです。

例えば

[toc depth="2" showcount="3"]

これは、「記事内に目次が3つ以上ある場合に2階層目まで表示」という指示になります。詳しくは石鷹さんの記事にて解説されています。

記事内に自動的に目次を表示

記事を書く度にショートコードを記述する手間を省いて、自動的に目次を表示させることも出来るようです。以下のコードをfunction.phpに記述しました。記事内で最初に登場するh2タグの直前に目次のショートコードを記述するようにしています。

function add_toc_content( $content ) {
	if ( is_single() ) {

		$shortcode = '[toc showcount="2" depth="2"]';

		$pattern = '/<h2.*?>/i';
		if ( preg_match( $pattern, $content, $matches ) ) {
			$content = preg_replace( $pattern, $shortcode . $matches[0], $content, 1 );
		}
	}
	return $content;
}

add_filter( 'the_content', 'add_toc_content');

まとめ

目次を書くメリットは最初に述べた通り、読者の方が求める情報により早く辿り着けるようにアシストすることにあります。数あるブログの中からせっかくこの記事に来て下さったわけですから、おもてなしという意味でもぜひ目次を設置してみてはいかがでしょうか。