首页
留言反馈
网站导航
推荐
毒鸡汤
Search
1
非插件为typecho 文章生成微海报分享
18,938 阅读
2
主题移动端,样式下添加二级分类
15,461 阅读
3
主题 添加author page
14,770 阅读
4
主题添加移动端下边栏
12,779 阅读
5
EMlog添加评论者邮箱等级
9,122 阅读
typecho
dynamic
SuiYu
Emlog
xiuno
登录
/
注册
Search
标签搜索
代码
xiuno
php
css
typecho
评论
模板
say
js
修改教程
标签
珍惜
努力
recommend
善良
样式
调用
微笑
颜色
插件
Vincent
累计撰写
151
篇文章
累计收到
184
条评论
首页
栏目
typecho
dynamic
SuiYu
Emlog
xiuno
页面
留言反馈
网站导航
推荐
毒鸡汤
搜索到
1
篇与
的结果
2021-10-09
为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; } 使用方法把上面的代码放到主题文件functions.php最后一行之前继续在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); } }最后在需要输出文章目录的位置调用<?php getCatalog(); ?>即可这是通用的方法,具体到每个人使用时,可以根据自己的需求修改,不再赘述。
2021年10月09日
1,185 阅读
0 评论
8 点赞