Dragon
  • 欢迎来到主题派官网,主题源码,插件,模板下载。wordpress,thinkphp,discuz,织梦模板,小程序。
主题派主题派  2023-06-19 12:56 主题派 隐藏边栏 |   抢沙发  11 
文章评分 0 次,平均分 0.0

通过这个目录也能让访客大概的知道这篇文章的主要内容,大大提升了访客的体验。那么这一次的 Typecho 教程就教大家如何实现这个有趣的功能吧

一些Typecho 主题集成了文章目录功能,能在文章旁边列出一级级的目录,方便访客阅读比较长的文章,而且,通过这个目录也能让访客大概的知道这篇文章的主要内容,大大提升了访客的体验。那么这一次的Typecho 教程就教大家如何实现这个有趣的功能吧。

  • 代码来源: https://www.offodd.com/76.html

代码内容

不过毕竟是 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(); ?>即可

这是通用的方法,具体到每个人使用时,可以根据自己的需求修改,不再赘述。

除了给主题增加功能,希望这一篇Typecho 教程也能帮助到您:

「点点赞赏,手留余香」

还没有人赞赏,快来当第一个赞赏的人吧!

主题派给主题派打赏
×
予人玫瑰,手有余香
  • 2
  • 5
  • 10
  • 20
  • 50
2
支付

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

主题派
主题派 关注:0    粉丝:0 最后编辑于:2024-05-03
Wordpress主题,插件,源码商城

发表评论

表情 格式 贴图 链接 私密 签到 常用语
扫一扫二维码分享
×
艾瑞克网