WrdoPress 教程 ·

WordPress 纯代码文章内添加文章目录功能

WordPress 文章内添加文章目录功能,能让文章结构看起来更加清晰,也有利于SEO

其实也有插件可以实现该功能的,例如:Content Index for WordPress

当然,我的立场能不插件就不插件

将一下代码插入到主题functions.php中(仅限于H2的标题拿来做文章目录项)

// 文章内容添加文章目录
function content_index($content) {
  if(is_single()){
    $matches = array();
    $ul_li = '';
    $r = "/<h2>([^<]+)<\/h2>/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>\n";
        }
        $content = "\n<div id=\"article-index\"><h3><span>文章目录</span></h3>
                <ul id=\"index-ul\">\n" . $ul_li . "</ul>
            </div>\n" . $content;
    }
}
    return $content;
}

add_filter( "the_content", "content_index", 13 );
// 如果手机端不想显示的话,可以使用(二选一)
if ( !wp_is_mobile()){
	add_filter( "the_content", "content_index", 13 );
}

css的话,仅限于本站展示

#article-index{
	position: fixed;
    z-index: 1;
    top: 30%;
    right: 1%;
    clear: both;
    overflow: hidden;
    background: #FFF;
    -webkit-box-shadow: 0 5px 10px 0 rgba(146,146,146,.1);
    -moz-box-shadow: 0 5px 10px 0 rgba(146,146,146,.1);
    box-shadow: 0 5px 10px 0 rgba(146,146,146,.1);
    padding: 15px;
    width: 10%;
}
#article-index h3{
	font-size: 18px;
    color: #282828;
    font-weight: 400;
    margin: 0;
    text-transform: uppercase;
    padding-bottom: 10px;
    margin-bottom: 15px;
    position: relative;
}
#article-index h3:after {
    content: "";
    background-color: #19B5FE;
    left: 1px;
    width: 50px;
    height: 2px;
    bottom: -2px;
    position: absolute;
    -webkit-transition: 0.5s;
    -moz-transition: 0.5s;
    -ms-transition: 0.5s;
    -o-transition: 0.5s;
    transition: 0.5s;
}
#article-index ul{
	margin: 0 auto;
}
#article-index ul li{
	list-style: none;
}
#article-index ul li a{
	color: #333;
    font-size: 13px;
}
#article-index:hover h3::after{
	width: 70px;
}

以下为展示例子,看页面最右边效果

文章目录一

文章目录二

文章目录三

参与评论