WordPress无插件实现自动文章目录方法(自定义CSS样式)

麦子 定制开发4字数 1147阅读3分49秒阅读模式

我们是不是看到不少文章比较长有H2 H3等小标题的文章都用内容文章目录?这个当然是可以用插件实现。比如 Easy Table of Contents 插件是可以实现的,这里我们不用插件,直接用代码也可以实现,看看方法记录下来。

代码实现方法。

  1. //文章目录无插件实现
  2. function article_index($content) {
  3. $matches = array();
  4. $ul_li = '';
  5. $r = '/<h([2-6]).*?\>(.*?)<\/h[2-6]>/is';
  6. if(is_single() && preg_match_all($r, $content, $matches)) {
  7. foreach($matches[1] as $key => $value) {
  8. $title = trim(strip_tags($matches[2][$key]));
  9. $content = str_replace($matches[0][$key], '<h' . $value . ' id="title-' . $key . '">'.$title.'</h2>', $content);
  10. $ul_li .= '<li><a href="#title-'.$key.'" title="'.$title.'">'.$title."</a></li>\n";
  11. }
  12. $content = "\n<div id=\"article-index\">
  13. <strong>文章目录</strong>
  14. <ul id=\"index-ul\">\n" . $ul_li . "</ul>
  15. </div>\n" . $content;
  16. }
  17. return $content;
  18. }
  19. add_filter( 'the_content', 'article_index' );

添加到 Functions.php 里。

  1. #article-index {
  2. -moz-border-radius: 6px 6px 6px 6px;
  3. border: 1px solid #DEDFE1;
  4. float: right;
  5. margin: 0 0 15px 15px;
  6. padding: 0 6px;
  7. max-width: 200px;
  8. line-height: 23px;
  9. }
  10. #article-index strong {
  11. border-bottom: 1px dashed #DDDDDD;
  12. display: block;
  13. line-height: 30px;
  14. padding: 0 4px;
  15. }
  16. #index-ul {
  17. margin: 0;
  18. padding-bottom: 10px;
  19. padding-left: 0px;
  20. }
  21. #index-ul li {
  22. background: none repeat scroll 0 0 transparent;
  23. list-style-type: disc;
  24. padding: 0;
  25. margin-left: 20px;
  26. }

样式给一个,我们也可以自定义CSS样式。

投上你的一票
 
  • 本文由 麦子 发表于 2024年10月22日 00:44:09
  • 转载请务必保留本文链接:https://www.zhujipingjia.com/wpauto-list.html
  • WordPress 文章目录