Typecho Wiki
每一个作品都值得被记录

Typecho 主题集成文章目录功能

Typecho维基君Typecho教程 • 2537次浏览 • 发布 2019-03-18 • 更新 2019-03-18
极致加速的V2Ray 助您畅享全球网络 & 搬瓦工VPS最新优惠码
🛜自用大流量超低月租手机卡推荐榜单 #拒绝流量焦虑

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

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.Wiki所有文章均包含本声明。
本文检索关键词:typecho
厂商投放

【腾讯云】🎉五一云上盛惠!云服务器99元/月续费同价!

腾讯云五一劳动节海量产品 · 轻松上云!云服务器首年1.8折起,买1年送3个月!超值优惠,性能稳定,让您的云端之旅更加畅享。快来腾讯云选购吧!

广告
添加新评论 »