在瀏覽百度知道的時候,你是否發現右上角有一列目錄,點選之後直接跳轉到本頁相對應的位置,如果你的 WordPress 文章博文目錄比較清晰的話是不是很容易就能讓訪客找到自己感興趣額的東西呢,這是肯定的哇,但是怎麼實現呢,下面 Themeidea 就教你實現此功能
1,將下面的程式碼寫入 functions.php

function article_index($content) {
    $matches = array();
    $ul_li = '';
    $r = "/<h3>([^<]+)</h3>/im";
    if(preg_match_all($r, $content, $matches)) {
        foreach($matches[1] as $num => $title) {
            $content = str_replace($matches[0][$num], '<h2 id="title-'.$num.'">'.$title.'</h2>', $content);
            $ul_li .= '<li><a href="#title-'/spanspan./spanspan%20style="color: #000088">$num.'" title="'.$title.'">'.$title."</a></li>
";
        }
        $content = "
<div id="article-index">
                <b>[文章目錄]</b>
                <ul id="index-ul">
" . $ul_li . "</ul>
            </div>
" . $content;
    }
    return $content;
}
add_filter( "the_content", "article_index" );

2,使用 CSS 對其進行美化

#article-index {background:#F7F7F7;-moz-border-radius: 6px 6px 6px 6px;border: 1px solid #DEDFE1;float: right;margin: 5px 0 5px 15px;padding: 0 6px;width: 280px;line-height: 24px;}
#article-index b {border-bottom: 1px dashed #DDDDDD;display: block;line-height: 30px;padding: 0 4px;}
#index-ul {margin: 0;padding-bottom: 5px;}
#index-ul li {background: none repeat scroll 0 0 transparent;list-style-type: disc;padding: 0;margin-top: 5px;margin-bottom: 5px;margin-left: 20px;}
#index-ul a{text-decoration:none;}

缺點:

  • 只支援 h3 標籤
  • 文章分頁啟用以後,只能在第一頁顯示
  • 不能實現分級目錄