文章目录免插件的简单实现方法

文章目录免插件的简单实现方法

去过百度百科的人可能都会注意到,几乎每篇文章的开头都会有一个目录,点击目录中的标题可以快速到达文章中的具体内容位置,如:Marketiva。这样可以方便读者在篇幅较长的文章中找到他们想看的内容,相当于词典中的索引功能。本文介绍的代码实现的就是这样的功能:为文章设置一个清晰的内容导航,读者可以在阅读之前知道这篇文章的大概结构,点击后到达想看的部分,而且可以增加一些内链、锚文本和关键词,对 SEO 也有帮助。具体效果见本文右侧的文章目录。

其实实现这样的功能还是比较简单的,也就是在文章内容中插入标题标签,然后生成目录。下面是我写的一段简单代码,用文本编辑器打开当前主题目录下的 functions.php,将以下代码放到 <?php 下面即可(记得用 UTF-8 编码保存,否则中文会乱码):

function article_index($content) {
    /**
     * 名称:文章目录插件
     * 作者:露兜
     * 博客:http://www.ludou.org/
     * 最后修改:2011年2月10日
     */
    $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],
                '<h4 id="title-' . $num . '">' . $title . '</h4>',
                $content
            );
            $ul_li .= '<li><a href="#title-' . $num . '" title="' . $title . '">' . $title . "</a></li>\n";
        }

        $content = "\n<div id=\"article-index\">\n<strong>文章目录</strong>\n<ul id=\"index-ul\">\n" . $ul_li . "</ul>\n</div>\n" . $content;
    }

    return $content;
}

add_filter('the_content', 'article_index');

使用说明

在编辑文章的时候,切换到 HTML 模式,将需要添加到目录中的标题用 <h3></h3> 括起来就可以了,如 <h3>我是索引标题</h3>。当然你也可以用其他标签,如 <h1><p> 等,将以上代码中的 h3 改成你自己的标签名称就可以了。

上面这段代码只是在文章显示的时候插入文章目录,并不会修改你的文章内容。以上代码也不包括样式美化代码,所以只添加以上代码时,文章目录看起来会比较混乱,你还得自己添加一些 CSS 代码来美化这个目录。如果你不会 CSS,可以用我写的,将以下 CSS 代码放到主题目录下的 style.css 中即可(并不是每个网站都适用):

#article-index {
    -moz-border-radius: 6px 6px 6px 6px;
    border: 1px solid #DEDFE1;
    float: right;
    margin: 0 0 15px 15px;
    padding: 0 6px;
    width: 200px;
    line-height: 23px;
}

#article-index strong {
    border-bottom: 1px dashed #DDDDDD;
    display: block;
    line-height: 30px;
    padding: 0 4px;
}

#index-ul {
    margin: 0;
    padding-bottom: 10px;
}

#index-ul li {
    background: none repeat scroll 0 0 transparent;
    list-style-type: disc;
    padding: 0;
    margin-left: 20px;
}

Leave a Reply