WordPress 文章目录免插件代码方法

现在网站开始流行给页面添加目录,方便访客浏览,其实维基百科很早就在使用。WordPress平台文章目录的生成方式有很多,省事就是直接使用插件,但几个经典插件久未更新,而且多在文章内展示。百度搜了下找到下面的免插件代码方法,完成后文章目录放在侧边栏,会随着页面滚动保持跟随。

PHP 代码

  1. //文章目录
  2. function article_index() {
  3.   if (is_singular()) //判断文章页
  4.   {
  5.     global $post;
  6.     $matches = array();
  7.     $ul_li = '';
  8.     $content = $post - > post_content;
  9.     $index_div = '';
  10.     $listnum = 0;
  11.     $titl_regex = '~<h([34])>(.+)</h([34])>~'; //匹配两级标题h3和h4
  12.     if (preg_match_all($titl_regex$content$matches)) { //使用$titl_regex匹配标题
  13.       foreach($matches[2] as $num => $title) {
  14.         $titlnum = $matches[1][$num];
  15.         $title = preg_replace('~<[^>]+>~', ''$title);
  16.         if ($titlnum == 4) { //h4标题
  17.           $h4num++;
  18.           $ul_li. = '<li class="listh4"><a href="#title-'.$num.'" title="'.$title.'"><span class="listnum">'.$h4num.'</span>'.$title.'</a></li>';
  19.         } else { //h3标题
  20.           $h3num++;
  21.           $h4num = 0;
  22.           $ul_li. = '<li><a href="#title-'.$num.'" title="'.$title.'"><span class="listnum">'.$h3num.'</span>'.$title.'</a></li>';
  23.         }
  24.       }
  25.       $index_div = '<div id="s1"><h3>文章目录</h3><ul id = "index-ul" >'.$ul_li.'</ul> </div>';
  26.     }
  27.     echo $index_div;
  28.   }
  29. }
  30. function article_titl($content) {
  31.   $matches = array();
  32.   $titl_regex = "~<h([34])>(.+)</h([34])>~";
  33.   if (preg_match_all($titl_regex$content$matches)) {
  34.     foreach($matches[2] as $num => $title) {
  35.       $content = preg_replace('~'.preg_quote($matches[0][$num], '/').'~', '<h'.$matches[1][$num].' id="title-'.$num.'">'.$title.'</h'.$matches[1][$num].'>', $content, 1);
  36.     }
  37.   }
  38.   echo $content;
  39. }
  40. add_filter('the_content', 'article_titl');

使用两级标题h3和h4,对于使用h2和h3,只需将~<h([34])>(.+)</h([34])>~更改为~<h([23])>(.+)</h([23])>~,如果使用更多级目录如h2、h3和h4,就需要改成~<h([234])>(.+)</h([234])>~,对应的if条件语句增加对h2的处理即可。

CSS 样式化

CSS样式化要针对网站的实际HTML结构来,下面是本站的相应CSS:

  1. /*目录单行显示*/
  2. #s1 li a {
  3.     display:block;
  4.     text-overflow:ellipsis;
  5.     overflow:hidden;
  6.     white-space:pre;
  7.     line-height:2
  8. }
  9. /*目录编号样式*/
  10. .listnum {
  11.     padding:.0625em .4em;
  12.     margin-right:.75em;
  13.     font-size:.875em;
  14.     background:#bbb;
  15.     border-radius:100%;
  16.     color:#fff;
  17.     transition:.075s
  18. }
  19. #s1 li:hover .listnum {
  20.     background:#03A9F4;
  21.     transition:.1s
  22. }
  23. /*h4标题目录缩进*/
  24. li.listh4 {
  25.     padding-left:2em;
  26.     font-size:.85em
  27. }

代码来自https://xinyo.org/archives/65879#s1

效果如图

版权声明:
作者:水东柳
链接:https://shuidl.com/216.html
来源:水东柳博客
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
< <上一篇
下一篇>>