探索建站和运维乐趣

WordPress 代码实现文章目录效果 自定义漂浮位置

我们老部落在前面文章中有介绍到Easy Table of Contents插件可以快速实现网站内容自动实现文章目录的效果,设置也是相对简单的,可以实现自动定位浮动以及自定义样式且默认有多种样式展现效果,一般我们网站都有使用文章目录功能。如果我们希望尽可能的少用插件占用服务器资源和网站带宽,我们可以使用这篇文章整理的无插件实现自动文章目录。

在这里我们可以在当前网站主题中的Functions.php文件中添加下面的代码。

//文章目录 Edit By laobuluo.com
function article_index($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-index\">
<strong>文章目录</strong>
<ul id=\"index-ul\">\n" . $ul_li . "</ul>
</div>\n" . $content;
}
return $content;
}
add_filter( 'the_content', 'article_index' );

@media screen and (max-width:600px) {
	#article-index {
    width: 100% !important;
}
}

不用设置,直接默认即可。

/* 文章目录样式 laobuluo.com */
#article-index {
-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-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;
}
#index-ul a {
	color: #4c4c4c;
}
#index-ul a:hover {
	color: #009cee;
}

然后我们可以在当前主题中的CSS样式文件中添加样式,样式我们可以根据实际需求修改,设置定义的漂浮位置。默认是将文章目录右上漂浮的,我们可以调整样式。

赞(2)
转载保留:老部落 » WordPress 代码实现文章目录效果 自定义漂浮位置


关注公众号『老蒋朋友圈』

获取更多建站运营运维新知!
互联网创业、前沿技术......