<?php
/**
* @param $content
* @return mixed|string
* @author DingLipeng<https://www.gznotes.com>
* @last_modify 2015-08-22
*/
function article_index($content) {
if (!is_singular()) {
return $content;
}
$index = '';
$ul = '';
$arr = array();
$pattern = '/<h([2-6]).*?\>(.*?)<\/h[2-6]>/is';
if (preg_match_all($pattern, $content, $arr)):
$count = count($arr[0]);
foreach ($arr[1] as $k => $v) {
//添加列表头
if ($k <= 0) {
$index = '<ul class="ljfl">'; //顶级
} else {
if ($v > $arr[1][$k - 1]) {
if ($v - $arr[1][$k - 1] == 1) {
$index.= '<ul>'; //上层小,层级高,当前为子层,先输出ul
} elseif ($v == $arr[1][$k - 1]) {
} else {
$index.= '文章目录层级不合法';
return false;
}
}
}
$title = strip_tags($arr[2][$k]);
$content = str_replace($arr[0][$k], '<h' . $v . ' id="index-' . $k . '">' . $title . '</h' . $v . '>', $content);
$index.= '<li class="h-' . $v . '"><a rel="contents chapter" href="#index-' . $k . '">' . $title . '</a></li>';//输出本层li
//列表封闭规则
if ($k < $count - 1) {
if ($v > $arr[1][$k + 1]) { //当前层大于下一层,本层结束,封底
$c = $v - $arr[1][$k + 1];
for ($i = 0;$i < $c;$i++) {
$ul.= '</ul>';
$index.= $ul;
$ul = '';
}
}
} else {
$index.= '</ul>';
}
}
$index = '<div id="ribs_article_nav" class="p-3 border w-50 mb-3"><div id="article_nav_title"><i class="fa fa-bars mr-2"></i>文章大纲</div><nav class="mt-3" role="navigation">' . $index . '</nav></div>';
$content = $index . $content;
endif;
return $content;
}
add_filter("the_content", "article_index");