说明:如果你不懂代码想使用插件可以查看wordpress文章目录插件:Content Index for WordPress
相信大家再写博文过程中,如果一遍文章内容比较多的时候希望通过文章头部的目录导航来让读者清新知道文章讲述的内容,及内容包含的各个模块。今天wordpress教程网就为大家介绍如何生成文章目录导航。
wordpress文章目录导航功能实现方法
要实现这个功能其实还比较简单的,只要在博客中指定好索引标签,然后通过以下代码将索引的标签内容读取出来生成目录即可。
将以下代码加入到你主题的functions.php末尾。
function article_index($content) {
/**
* 名称:文章目录插件
* 作者:wordpress教程网
* 博客:http://www.shouce.ren/
* 最后修改:2013年4月2日
*/
$matches = array();
$ul_li = '';
$r = "/<h3>([^<]+)<\/h3>/im"; // 此处设置标签为<h3>,可根据自己的需求来更改
if(preg_match_all($r, $content, $matches)) {
foreach($matches[1] as $num => $title) {
$content = str_replace($matches[0][$num], '<h3 id="title-'.$num.'">'.$title.'</h3>', $content); //获取<h3>标签中的内容
$ul_li .= '<li><a href="#title-'.$num.'" title="'.$title.'">'.$title."</a></li>\n"; //将<h3>标签中的内容提起出来
}
$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" );
使用说明
本文是以h3为目录生成的标签,在编辑文章的时候,切换到HTML模式,将需要添加到目录中的标题用<h3>和</h3>括起来就可以了,如<h3>我是索引标题</h3>。当然你也可以用其他标签,如<h1>,<p>等。
上面这段代码只是在文章显示的时候插入文章目录,并不会修改你的文章内容。以上代码也不包括样式美化代码,所以只添加以上代码,文章目录看起来一篇混乱,所以你得自己添加一些css代码来美化一下这个目录。如果你不会css,可以用我写的,将以下css代码放到主题目录下的style.css中就可以了(并不是每个网站都适用):
#article-index {
-moz-border-radius: 6px 6px 6px 6px;
border: 1px solid #DEDFE1;
float: right;
margin: 0 0 15px 15px;
padding: 0 6px;
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;
}
#index-ul li {
background: none repeat scroll 0 0 transparent;
list-style-type: disc;
padding: 0;
margin-left: 20px;
}