WordPress文章目录实现代码

Wordpress 思享 319浏览

对于长篇的文章,如果没有目录浏览体验会大打折扣,而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 样式代码

#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;
}

大概实现效果如下图:

wordpress目录

总结

代码实现此功能简单易用,确定是还需要引入js代码实现目录的折叠和展现,除此之外也需要调整样式更美观

推荐阅读

WordPress4.9分支最新版更新至4.9.25

WordPress其实很早之前就已经更新到6.x版本了,不过本博客一直使用4.9分支。幸运的是,这个版本的分支仍在更新中。该版本已于2024年1月31日更新至4.9.25版本。 下载链接 [下载]https://cn.wordpress.......

纯代码实现wordpress附件页面重定向到文章或首页

前几天发现wordpress网站有评论留言的回顾。结果一看就是附件页面的垃圾评论。这才发现原来wordpress上传的附件也会有对应的页面。难怪之前收录了很多附件页面,但是我的机器人禁止了,忘记了。本来以为会禁用,结果只找到了在线使用插件的方法。最后......

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘fake_update_callback’

这是当一个被挂钩的函数名与挂钩关联不匹配时…这可能发生在重命名一个函数时,而不是在挂钩关联中重命名函数名时。如果强迫症受不了wordpress的主题提示,可以使用插件WP降级将版本设置为当前版本。...