一些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教程也能幫助到您: