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

Gavin Wu 2019年08月05日 8:08 Typecho 1,845 Views

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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 条

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Top