wordpress主题:添加文章目录
发表日期:2011-10-08 作者:DH分类:编程技术 标签: wordpress
1 缘起
有一次,我在逛博客,看到有个博客(清水稀饭)很有意思,竟然像百度百科一样,有标题!这种标题wiki也有,是一种有助于读者快速掌握文章内容,方便读者在篇幅较长的文章中找到他们想看的内容,这个也就相当于索引。作者也提供了方法,我学着做了一个,扩展了一些功能。支持双层的标题。参考文章有: WordPress文章目录插件2 示例
看我的博客文章的右上角的目录索引,可以隐藏的那个。具体如图:
3 代码
要完成这个功能,需要有前台的css支持和后台的代码。这里以我的为例说明,各位看官需要更具自己的情况修改代码和css。3.1 后台部分
后台主要实现的是对content的过滤,需要替换字符和添加目录。代码是这样的。保存为article_index.php
([^<]+)<\/(h[2-5])>/im";
if(preg_match_all($r, $content, $matches))
{
foreach($matches[2] as $num => $title)
{
//if($num==0)
if(true)
{
$content = str_replace($matches[0][$num], '<'.$matches[1][$num].' id="title-'.$num.'">'.$title.''.$matches[3][$num].'>', $content);
}
else
{
$content = str_replace($matches[0][$num], '<'.$matches[1][$num].' id="title-'.$num.'">'.$title.''.$matches[3][$num].'>top', $content);
}
if($matches[1][$num] == 'h2')
$ul_li .= '
正文索引[ 隐藏 ]
- ' . $ul_li . '
#生成目录
include("article_index.php");
3.2 前台css部分
css是调整显示的,让这个好看一点。保存为article_index.css。
#article-index {
float: right;
position: relative;
margin:0 0 10px 10px;
width:180px;
border-radius: 6px;
-webkit-border-radius:6px;
-khtml-border-radius:6px;
-moz-border-radius:6px;
border: 1px solid #aaa
}
#index-title{
border-radius: 7px 7px 0 0;
padding: 0 0 1px 8px;
border-bottom: 1px solid #aaa;
background-color: #EEE
}
#the-index-title {
line-height: 1.6;
color: #019858;
font-weight: bold
}
#show-index{
cursor: pointer;
margin-left:8px;
margin-right:8px
}
#index-ul {
list-style: none;
padding: 4px 5px 4px 7px;
margin: 0
}
#level2{
padding-left: 10px;
}
#level3{
padding-left: 25px;
}
#content_title{
position:relative
}
#article-index-top{
position:absolute;
top:5px;
right:10px
z-index: 111;
}
需要在header.php中包含
3.2 前台js部分
js是用来隐藏目录和显示目录使用的。保存为article_index.js。
$(document).ready(function(){
$("#show-index").click(function()
{
if($("#show-index").html()=="[ 隐藏 ]")
{
$("#index-ul").fadeOut("normal");
$("#show-index").html("[ 展开 ]");
}else if($("#show-index").html()=="[ 展开 ]")
{
$("#index-ul").fadeIn("normal");
$("#show-index").html("[ 隐藏 ]");
}
else
{
return false;
}
});
});
需要在header.php中包含