炭火Blog
HOME
ブログの運営

サイドバーと記事内に表示できる目次をプラグインなしで作る

※このページにはプロモーションが含まれています。

Table of Contents

目次をプラグイン無しで表示させるコードの紹介です。参考にしたサイトは最後に掲載していますので、ぜひご覧ください。

元のコードとの違いは見出しにクラスをつけるとその見出しは目次に表示されない機能を、私には不要なので取り除いた点です。その機能が必要な方は参照ページのコードをお使いください。

このコードでできることは

コードはすべてfunctions.phpに記載します。

4つのリストのうちから選び、カッコ内のコード番号のコードをfunctions.phpに追加することで目次が表示されるようになります。

  1. ショートコードで目次を表示(リンクなし)(コード番号 1・2)
  2. ショートコードで目次を表示(リンクあり)(コード番号 1・4・5)
  3. 投稿記事内で目次を表示(リンクなし)(コード番号 1・3)
  4. 投稿記事内で目次を表示(リンクあり)(コード番号 1・3・4)

目次を表示するためのコード

コード番号 1

目次表示のためのコード。すべての場合に使用します。

function get_toc($content) {
$headings = get_headings($content);
ob_start();
echo "<div>";
if (wp_is_mobile()){
echo "<span>目次</span>";
}
parse_toc($headings, 0, 0);
echo "</div>";
return ob_get_clean();
}
function parse_toc($headings, $index, $recursive_counter) {
if($recursive_counter > 60 || !count($headings)) return;
$last_element = $index > 0 ? $headings[$index - 1] : NULL;
$current_element = $headings[$index];
$next_element = $index < count($headings) ? $headings[$index + 1] : NULL;
if($current_element == NULL) return;
$tag = intval($headings[$index]["tag"]);
$id = $headings[$index]["id"];
$name = $headings[$index]["name"];
if($last_element == NULL || $last_element["tag"] < $tag) echo "<ul>";
echo "<li>";
echo "<a href='#" . $id . "'>" . $name . "</a>";
if(intval($next_element["tag"]) > $tag) {
parse_toc($headings, $index + 1, $recursive_counter + 1);
}
echo "</li>";
if(intval($next_element["tag"]) == $tag) {
parse_toc($headings, $index + 1, $recursive_counter + 1);
}
if($next_element == NULL || $next_element["tag"] < $tag) echo "</ul>";
if($next_element != NULL && $next_element["tag"] < $tag) {
parse_toc($headings, $index + 1, $recursive_counter + 1);
}
}
function get_headings($content) {
$headings = array();
preg_match_all("/<h([1-3])(.*)>(.*)<\/h[1-3]>/", $content, $matches);
for($i = 0; $i < count($matches[1]); $i++) {
$headings[$i]["tag"] = $matches[1][$i];
$att_string = $matches[2][$i];
preg_match("/id=\"([^\"]*)\"/", $att_string , $id_matches);
$headings[$i]["id"] = $id_matches[1];
$att_string = $matches[2][$i];
$headings[$i]["name"] = $matches[3][$i];
}
return $headings;
}

コード番号 2

目次から見出しに飛ばない場合に使用するショートコード作成用コード。

function toc_shortcode() {
return get_toc(get_the_content());
}
add_shortcode('TOC', 'toc_shortcode');

コード番号 3

投稿記事内に目次を表示させるためのコード。

function add_table_of_content($content) {
if (!is_single()) return $content;
$paragraphs = explode("</p>", $content);
$paragraphs_count = count($paragraphs);
$middle_index= absint(floor($paragraphs_count / 2));
$new_content = '';
for ($i = 0; $i < $paragraphs_count; $i++) {
if ($i === 0) {
$new_content .= get_toc($content);
}
$new_content .= $paragraphs[$i] . "</p>";
}
return $new_content;
}
add_filter('the_content', 'add_table_of_content');

if ($i === 0) {の0はPタグの下に目次を表示させる設定数値になります。0だと一番上に目次が表示され、1だと1段落の下に表示されます。

if ($i === 0) {

コード番号 4

見出しにIDをつけるコード。

function auto_id_headings( $content ) {
$content = preg_replace_callback('/(\<h[1-3](.*?))\>(.*)(<\/h[1-3]>)/i', function( $matches ) {
if(!stripos($matches[0], 'id=')) {
$matches[0] = $matches[1] . $matches[2] . ' id="' . sanitize_title( $matches[3] ) . '">' . $matches[3] . $matches[4];
}
return $matches[0];
}, $content);
return $content;
}
add_filter('the_content', 'auto_id_headings');

コード番号 5

見出しにIDを付けた場合に使うショートコード用のコード。

function toc_shortcode() {
return get_toc(auto_id_headings(get_the_content()));
}
add_shortcode('TOC', 'toc_shortcode');

おそらくサイドバーと投稿記事内に同時表示も可能ですが、必要性が無いと思い試していません。

How to create a Table of Contents in WordPress (without plugin, my free code)

参照サイトです、ありがとうございます。

最後までお読みくださり、誠にありがとうございます。

WordPressオリジナルテーマ制作入門
amazon.co.jp
【Amazon.co.jp限定】1冊ですべて身につくWordPress入門講座(DL特典:【100ページ超の大特典!】フルサイト編集に“対応していない”テーマのカスタマイズ方法)
amazon.co.jp

週間アクセスランキング

このブログを書いている人

管理者 ほんだ

数多くあるブログの中で、このページをお読みくださりありがとうございます。このブログは、炭火で美味しいものを作ることを中心に、日々の趣味についてを文章にすることで、WordPressを使ってのWebページ作成を忘れないようにしています。熱帯魚の世話や野菜の栽培、Linuxについて興味のあることを、つたない文章で綴っています。兵庫県在住です。