1. <?php
    2. /**
    3. * @param $content
    4. * @return mixed|string
    5. * @author DingLipeng<https://www.gznotes.com>
    6. * @last_modify 2015-08-22
    7. */
    8. function article_index($content) {
    9. if (!is_singular()) {
    10. return $content;
    11. }
    12. $index = '';
    13. $ul = '';
    14. $arr = array();
    15. $pattern = '/<h([2-6]).*?\>(.*?)<\/h[2-6]>/is';
    16. if (preg_match_all($pattern, $content, $arr)):
    17. $count = count($arr[0]);
    18. foreach ($arr[1] as $k => $v) {
    19. //添加列表头
    20. if ($k <= 0) {
    21. $index = '<ul class="ljfl">'; //顶级
    22. } else {
    23. if ($v > $arr[1][$k - 1]) {
    24. if ($v - $arr[1][$k - 1] == 1) {
    25. $index.= '<ul>'; //上层小,层级高,当前为子层,先输出ul
    26. } elseif ($v == $arr[1][$k - 1]) {
    27. } else {
    28. $index.= '文章目录层级不合法';
    29. return false;
    30. }
    31. }
    32. }
    33. $title = strip_tags($arr[2][$k]);
    34. $content = str_replace($arr[0][$k], '<h' . $v . ' id="index-' . $k . '">' . $title . '</h' . $v . '>', $content);
    35. $index.= '<li class="h-' . $v . '"><a rel="contents chapter" href="#index-' . $k . '">' . $title . '</a></li>';//输出本层li
    36. //列表封闭规则
    37. if ($k < $count - 1) {
    38. if ($v > $arr[1][$k + 1]) { //当前层大于下一层,本层结束,封底
    39. $c = $v - $arr[1][$k + 1];
    40. for ($i = 0;$i < $c;$i++) {
    41. $ul.= '</ul>';
    42. $index.= $ul;
    43. $ul = '';
    44. }
    45. }
    46. } else {
    47. $index.= '</ul>';
    48. }
    49. }
    50. $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>';
    51. $content = $index . $content;
    52. endif;
    53. return $content;
    54. }
    55. add_filter("the_content", "article_index");