首页 » 近期 » 浏览内容

给你的WordPress文章添加目录索引

6599 0
标签:
目录[ 隐藏 ]

用插件是不错的选择,简单,不需要修改模板函数,CSS不会的也不用担心,喜欢折腾滴:下面我们来粘贴免插件实现”目录索引”的方法

1.在模板函数中添加代码

第一个步骤

//载入文章目录索引测试
function article_index($content) {
$matches = array();
$ul_li = '';
$r = "/<h3>([^<]+)<\/h3>/im";
if(preg_match_all($r, $content, $matches)) {
foreach($matches[1] as $num => $title) {
$content = str_replace($matches[1][$num], '<h3 id="-'.$num.'">'.$title.'</h3>', $content);
$ul_li .= '<li><a href="#-'.$num.'" title="'.$title.'">'.$title."</a></li>\n";
}
$content = '<div id="article-index">
<div id="index-title"><span id="the-index-title">正文索引</span><span id="show-index">[ 隐藏 ]</span></div>
<div id="index-ul"><ul>' . $ul_li . '</ul></div></div>' . $content;
}
return $content;
}
add_filter( "the_content", "article_index" );

2.目录索引的实现

文章内容中添加标题标签

现在要实现”目录索引”你需要做的就是在各个标题的前面添加 代码”目录索引标题”代码
注意两点:”代码” 是可以自定义的,修改成你所想要的然后替换上面模板函数第4行代码即可
看截图吧:

3.添加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;
}
/* 测试文章目录借宿 repeat-x*/

提别需要注意的是在编辑模板函数与css样式的时候请先复制里面的内容粘贴于一个新建立的文本文档(不保存,不会乱码),如果错误直接重新还原原始的,如果保存后wordpress后台加载失败,那么你就得用ftp上传进去了(保存原始里面的为UTF-8)


4.设置JS控制隐藏显示效果

在互联网搜索了到了,js控制隐藏显示效果的方法

将下端JS代码集成到主题文件夹js里面,或者新建立这段js代码并上传至网站
这是段使你的wordpress文章索引 能有显示,隐藏目录的特效的代码(效果右上角)

$(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;
 }
 });
});

第二步,在wordpress主题header.php(顶部)中引入,如新建为mulu.js,则添加下端引用(不知道具体放在位置的看我博客源文件),我也是新手,嘿,,, 如果你将上段JS代码集成到主题内js,这一步可以跳过

<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/mulu.js"></script>
..

联系我 Contact Me

回到页首