在浏览百度知道的时候,你是否发现右上角有一列目录,点击之后直接跳转到本页相对应的位置,如果你的 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-'.$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 标签
  • 文章分页启用以后,只能在第一页显示
  • 不能实现分级目录