纯代码实现WordPress文章添加可自定义悬浮位置的目录

在之前的文章中,我们介绍了Easy Table of Contents插件。它可以自动为文章生成目录,设置简单,支持浮动定位、样式自定义,并提供多种默认样式可供选择。对于大多数网站来说,这的确是一个便捷的文章目录解决方案。

不过,如果您希望尽量减少插件对服务器资源和网站带宽的占用,也可以通过代码实现类似功能,无需依赖插件。下面,我们来介绍如何在当前网站主题的 functions.php​ 文件中添加相关代码,以纯代码的方式自动生成文章目录。

//文章目录 Edit By itbulu.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' );



     (adsbygoogle = window.adsbygoogle || []).push({});


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


直接默认:

/* 文章目录样式 itbulu.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样式文件中添加样式,样式我们可以根据实际需求修改,设置定义的漂浮位置。默认是将文章目录右上漂浮的,我们可以调整样式。

投上你的一票

原创文章,转载请注明出处:https://www.itbulu.com/codewplist.html

上一篇 2026年1月27日 09:42
下一篇 1小时前