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

554次阅读
没有评论

共计 2228 个字符,预计需要花费 6 分钟才能阅读完成。

现在网站开始流行给页面添加目录,方便访客浏览,其实维基百科很早就在使用。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

效果如图

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

正文完
 
水东柳
版权声明:本站原创文章,由 水东柳 2018-05-19发表,共计2228字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)