sakoda

現在のページから、hタグを拾って目次を作成したい。

0

現在のページから全てのhタグを取得して、自動で目次を作成したいです。ワードプレスではできたのですが、Movable Typeでやるとどのようなコードになるのでしょうか?


function add_index($content){
if (is_single()) {
$pattern = '/<h[1-6]>(.+?)<\/h[1-6]>/s';
preg_match_all($pattern, $content, $elements, PREG_SET_ORDER);

if (count($elements) >= 1) {
$toc = '';
$i = 0;
$currentlevel = 0;
$id = 'chapter-';

foreach ($elements as $element) {
$id .= $i + 1;
$replace_title = preg_replace('/<(h[1-6])>(.+?)<\/(h[1-6])>/s', '<$1 id="' . $id . '">$2</$3>', $element[0]);
$content = str_replace($element[0], $replace_title, $content);

if (strpos($element[0], '<h2') !== false) {
$level = 1;
} elseif (strpos($element[0], '<h3') !== false) {
$level = 2;
} elseif (strpos($element[0], '<h4') !== false) {
$level = 3;
} elseif (strpos($element[0], '<h5') !== false) {
$level = 4;
} elseif (strpos($element[0], '<h6') !== false) {
$level = 5;
}

while ($currentlevel < $level) {
if ($currentlevel === 0) {
$toc .= '<ol class="index__list">';
} else {
$toc .= '<ol class="index__list_child">';
}
$currentlevel++;
}

while ($currentlevel > $level) {
$toc .= '</li></ol>';
$currentlevel--;
}

// 目次の項目で使用する要素を指定
$toc .= '<li class="index__item"><a href="#' . $id . '" class="index__link">' . $element[1] . '</a>';
$i++;
$id = 'chapter-';
} // foreach

// 目次の最後の項目をどの要素から作成したかによりタグの閉じ方を変更
while ($currentlevel > 0) {
$toc .= '</li></ol>';
$currentlevel--;
}

$index = '<div class="single__index index" id="toc"><div class="index__title">目次<button class="index__button">閉じる</button></div>' . $toc . '</div>';
$h2 = '/<h2.*?>/i';

if (preg_match($h2, $content, $h2s)) {
$content = preg_replace($h2, $index . $h2s[0], $content, 1);
}
}
}
return $content;
}
add_filter('the_content', 'add_index');

返信(2)

| 返信する
  • こんにちは

    MTMLで実装ではなくJSを利用して実現してはどうでしょうか?

    jQueryのプラグインで手軽に実装できるものがあります。
    https://github.com/jgallen23/toc

  • 返信ありがとうございます
    jsを使って一度実装したんですが、目次のコードがページのソースに表示されませんでした。
    (検証ツールからページのソースを表示をクリックした時のこと。)
    ページソースに表示されるように実装したいので、jsは使えないという判断になりました。

返信する


カテゴリグループ

106 23

最新のトピック: test (2019年5月29日 sato)

フォーラムカテゴリー

21 76

最新のトピック: 公開終了日の取り消し (2013年10月18日 gsk)

174 498

最新のトピック: 現在の投稿の本文を取得したい (2019年10月28日 sakoda)

OpenID対応しています OpenIDについて