首页 Typecho Typecho免插件实现文章目录功能

Typecho免插件实现文章目录功能

Typecho添加主题目录的教程好像不是很多,而且我找到的仅有的几个都是前台JS实现的,总感觉这样不如后台实现来的好。既然Typecho找不到现成的,只好“曲线救国”,由于实现文章目录的原理是通用的,所以就去WP里找了,那可是大把大把的。

function createCatalog($obj) {    //为文章标题添加锚点
    global $catalog;
    global $catalog_count;
    $catalog = array();
    $catalog_count = 0;
    $obj = preg_replace_callback('/(.*?)/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 ''.$obj[3].'';
    }, $obj);
    return $obj;
}

function getCatalog() {    //输出文章目录容器
    global $catalog;
    $index = '';
    if ($catalog) {
        $index = ''."\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 .= ''."\n";
                } elseif ($catalog_depth > $prev_depth) {
                    $to_depth++;
                    $index .= ''."\n";
                } else {
                    $to_depth2 = ($to_depth > ($prev_depth - $catalog_depth)) ? ($prev_depth - $catalog_depth) : $to_depth;
                    if ($to_depth2) {
                        for ($i=0; $iis('single')) {
        $archive->content = createCatalog($archive->content);
    }
}

使用方法

  1. 把上面的代码放到主题文件functions.php最后一行之前

2.最后在需要输出文章目录的位置调用``即可

相关推荐

6 条评论

  • tnjc游客 2020年01月02日 19:37

    添加了代码,在文章中也有 好像还是没有显示

  • tnjc游客 2020年01月02日 19:39
    • jerrywcy游客 2020年02月21日 13:18

      应该要加到post.php里才有用吧

      • beiduoye游客 2020年02月25日 03:23

        加到哪个页面都可以,page页面 post或者header.php和footer.php其他页面 只要页面里有h1h2h3h4h5h6这些标签就行

  • 一剑隔世游客 2020年03月06日 06:17

    文章目录,曾经困扰了很久的问题。

  • Feed游客 2020年03月09日 17:00

    已转载并注明,感谢大佬分享。

发表回复

邮箱地址不会被公开。