1、先在 WordPress 当前主题文件下的 functions.php 文件里添加上以下 Php 代码:

function article_list($content) {
$matches = array();
$ul_li = '';
$r = '/<h([2-6]).*?\>(.*?)<\/h[2-6]>/is';
if(is_single() && preg_match_all($r, $content, $matches)) {
foreach($matches[1] as $key => $value) {
$title = trim(strip_tags($matches[2][$key]));
$content = str_replace($matches[0][$key], '<h' . $value . ' id="title-' . $key . '">'.$title.'</h2>', $content);
$ul_li .= '<li><a href="#title-'.$key.'" title="'.$title.'">'.$title."</a></li>\n";
}
$content = "\n<div id=\"article-list\">
<strong>文章目录</strong>
<ul id=\"list-ul\">\n" . $ul_li . "</ul>
</div>\n" . $content;
}
return $content;
}
add_filter( 'the_content', 'article_list' );

以上这段 Php 代码就是实现文章目录的主要代码,主要是匹配出文章内容中从 H2 到 H6 的标签里的内容,然后展现在文章目录中。

2、在当前主题模板的 style.css 里添加以下 Css 代码:

文章目录宽度本文中设置的 300Px,可以根据自己网站的文章页面的前端自身情况进行调整。


#article-list {
-moz-border-radius: 6px 6px 6px 6px;
border: 1px solid #DEDFE1;
float: right;
margin: 0 0 15px 15px;
padding: 0 6px;
width: 300px;
line-height: 23px;
}
#article-list strong {
border-bottom: 1px dashed #DDDDDD;
display: block;
line-height: 30px;
padding: 0 4px;
}
#list-ul {
margin: 0;
padding-bottom: 10px;
}
#list-ul li {
background: none repeat scroll 0 0 transparent;
list-style-type: disclosure-closed;
padding: 0;
margin-left: 20px;
color:#ff6900;
}
#list-ul a {
    color: #4c4c4c;
}
#list-ul a:hover {
    color: #009cee;
}
@media screen and (max-width:568px) {
    #article-list {
    width: 100% !important;
}
}

在 Css 代码的最后一部分中的最大 568 像素的时候,可以根据自身网站情况进行调整。