Loading...

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

教程分享2年前 (2022)发布 战东海
316 0 0
WordPress教程:WordPress无插件实现自动文章目录方法(自定义CSS样式)

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

代码实现方法。

//文章目录无插件实现
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="'.$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' );

添加到 Functions.php 里。

#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;
}
© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...

网址设置

网址样式切换

详细

网址卡片按钮

显示

布局设置

左侧边栏菜单

展开

搜索框设置

自定义搜索框背景

  • 骑行

  • 风景

自定义搜索框高度

  • 聚焦
  • 信息
  • 默认
自定义设置
TAB栏自定义颜色

背景颜色

文字颜色