Dynadot Jtti 搬瓦工 腾讯云

WordPress 使用纯代码方法自动生成并添加文章目录

GigsGigsCloud

大家使用 WordPress 建设网站的时候,尤其是撰写博客的时候,可能会想要自动生成文章目录,然后添加到文章里,这样会显得文章比较有条理,并且让人看起来比较清爽。今天就分享一下 WordPress 使用纯代码的方式,在文章内容里自动添加文章目录的方法。添加的位置在文章的右上方,会自动添加 h2 到 h6 的目录。

更新:推荐使用插件方式实现文章目录,参考《LuckyWP Table of Contents:WordPress 插件实现自动插入文章目录》。

一、文章目录代码

把下面的代码放到主题文件 functions.php 文件里即可:

//文章目录
function article_index($content) {
  $matches = array();
  $ul_li = '';
  $r = '/<h([2-6]).*?\>(.*?)<\/h[2-6]>/is';
  if(is_single() && preg_match_all($r, $content, $matches)) {
    foreach($matches[1] as $key => $value) {
      $title = trim(strip_tags($matches[2][$key]));
      $content = str_replace($matches[0][$key], '<h' . $value . ' id="title-' . $key . '">'.$title.'</h2>', $content);
      $ul_li .= '<li><a href="#title-'.$key.'" title="'.$title.'">'.$title."</a></li>\n";
    }
    $content = "\n<div id=\"article-index\">
    <strong>文章目录</strong>
    <ul id=\"index-ul\">\n" . $ul_li . "</ul>
    </div>\n" . $content;
  }
  return $content;
}
add_filter( 'the_content', 'article_index' );

二、CSS 样式代码

顺便再分享一下本站自己使用的 CSS:

#article-index {
  -moz-border-radius: 6px 6px 6px 6px;
  border: 1px solid #DEDFE1;
  float: right;
  margin: 0 0 15px 15px;
  padding: 0 6px;
  max-width: 200px;
  line-height: 23px;
}
#article-index strong {
  border-bottom: 1px dashed #DDDDDD;
  display: block;
  line-height: 30px;
  padding: 0 4px;
}
#index-ul {
  margin: 0;
  padding-bottom: 10px;
  padding-left: 0px;
}
#index-ul li {
  background: none repeat scroll 0 0 transparent;
  list-style-type: disc;
  padding: 0;
  margin-left: 20px;
}

这段代码最初是在网上找的,但是目前已经忘了出处。分享出来的原因是我自己暂时用不到,正好打理自己的网站的时候看到。

除了纯代码的方法,还有使用插件的方法实现文章目录的,明天我们继续分享。

Dynadot Hostwinds
赞(4)
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《WordPress 使用纯代码方法自动生成并添加文章目录
文章链接:https://oldtang.com/444.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。