一、文章目录代码
把下面的代码放到主题文件 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;
}
三、安装插件 Easy Table of Contents
我们可以在 WordPress 后台直接搜索进行安装,也可以下载后进行安装。
安装完成后,启用,然后进行一些简单的设置。本站推荐的设置如下:
- 选择需要支持的类型,建议选择 “文章” 和 “页面”,其他的根据自己需求选择。
- 选择需要自动插入的地方,同上。
- 选择显示位置,建议 top。
- 设置大于等于多少个标题的时候显示目录,根据自己的需求。
- 设置显示名称,如果是中文网站,可以把 “Table of Contents” 改成 “文章目录”。
- 选择是否需要自动编号,因为我习惯自己编号,所以这里不需要自动编号。
- 最后再选择一下浮动位置,建议浮动在右侧。
至此,我们就完成了 Easy Table of Contents 这个插件的安装和配置,enjoy it!
除了设置在文章和页面显示之外,我们还可以设置小工具,比如如果把小工具添加到侧边栏,那么就可以在侧边栏显示文章目录。如下图所示,添加起来非常简单




No comments:
Post a Comment