为Typecho主题集成文章目录功能(免插件实现文章目录功能)
Typecho添加主题目录的教程好像不是很多,而且我找到的仅有的几个都是前台JS实现的,总感觉这样不如后台实现来的好。既然Typecho找不到现成的,只好“曲线救国”,由于实现文章目录的原理是通用的,所以就去WP里找了,那可是大把大把的。
没多想,第一个就到WP果酱那里扒了他的插件的代码,因为我曾经也是水煮鱼大大的粉啊😭,他的几个作品我用的可以说是炉火纯青了。(自己写是不可能的,Ctrl+C+V 大法那么无敌😂)
代码内容
不过毕竟是WP下的东西,要移植到Typecho还是要改一改的,下面直接放出修改后的代码吧,使用方法继续往下看。
function createCatalog($obj) { //为文章标题添加锚点
global $catalog;
global $catalog_count;
$catalog = array();
$catalog_count = 0;
$obj = preg_replace_callback('/<h([1-6])(.*?)>(.*?)<\/h\1>/i', function($obj) {
global $catalog;
global $catalog_count;
$catalog_count ++;
$catalog[] = array('text' => trim(strip_tags($obj[3])), 'depth' => $obj[1], 'count' => $catalog_count);
return '<h'.$obj[1].$obj[2].'><a name="cl-'.$catalog_count.'"></a>'.$obj[3].'</h'.$obj[1].'>';
}, $obj);
return $obj;
}
function getCatalog() { //输出文章目录容器
global $catalog;
$index = '';
if ($catalog) {
$index = '<ul>'."\n";
$prev_depth = '';
$to_depth = 0;
foreach($catalog as $catalog_item) {
$catalog_depth = $catalog_item['depth'];
if ($prev_depth) {
if ($catalog_depth == $prev_depth) {
$index .= '</li>'."\n";
} elseif ($catalog_depth > $prev_depth) {
$to_depth++;
$index .= '<ul>'."\n";
} else {
$to_depth2 = ($to_depth > ($prev_depth - $catalog_depth)) ? ($prev_depth - $catalog_depth) : $to_depth;
if ($to_depth2) {
for ($i=0; $i<$to_depth2; $i++) {
$index .= '</li>'."\n".'</ul>'."\n";
$to_depth--;
}
}
$index .= '</li>';
}
}
$index .= '<li><a href="#cl-'.$catalog_item['count'].'">'.$catalog_item['text'].'</a>';
$prev_depth = $catalog_item['depth'];
}
for ($i=0; $i<=$to_depth; $i++) {
$index .= '</li>'."\n".'</ul>'."\n";
}
$index = '<div id="toc-container">'."\n".'<div id="toc">'."\n".'<strong>文章目录</strong>'."\n".$index.'</div>'."\n".'</div>'."\n";
}
echo $index;
}
使用方法
1. 把上面的代码放到主题文件functions.php
最后一行之前
2. 继续在functions.php
内搜索关键词function themeInit
如果有themeInit
这个函数,则在themeInit
这个函数内添加下面的代码
if ($archive->is('single')) {
$archive->content = createCatalog($archive->content);
}
如果没有themeInit
这个函数,则在functions.php
最后一行之前添加下面的代码
function themeInit($archive) {
if ($archive->is('single')) {
$archive->content = createCatalog($archive->content);
}
}
3. 最后在需要输出文章目录的位置调用<?php getCatalog(); ?>
即可
这是通用的方法,具体到每个人使用时,可以根据自己的需求修改,不再赘述。
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
是不是会PHP后想改啥就改啥,可惜我不会。
学
学
很不错
目测优于纯前端方案
看到了目录显示位置原来在右下角。能不能设置在文章左边空白出。进去一眼就能看到。
文章目录演示的文章在哪,我找了你说的《Initial主题”和“主题说明”那两篇文章里面有目录》还是没有看到,我自己根据教程写了代码,还是不行。求指导
感谢分享,抄走了.
学习了
感谢分享
博主,我看你归档里的年份也是H3标签。这个文章目录函数怎么样修改才能让归档里的H3标签也能使用文章目录呀。
function themeInit($archive) {
}
我这么写没有生效额。
博主怎么没用起来,看你博客居然没整这个目录。。。这么好的功能~
请问下,怎么设置默认打开[文章目录]功能
可以用js点击效果事件配合css就搞定了,我博客就是用的博主这个。我就是弄的默认显示打开文章目录。