最近几年,内容网站开始流行给页面添加目录,方便访客浏览,其实维基百科很早就在使用。WordPress平台文章目录的生成方式有很多,省事就是直接使用插件,但几个经典插件久未更新,而且多在文章内展示,我基于露兜博客中的代码,添加最多两级的目录,放在侧边栏,会随着页面滚动保持跟随。
PHP 代码
//文章目录
function article_index() {
if (is_singular()) //判断文章页
{
global $post;
$matches = array();
$ul_li = '';
$content = $post - > post_content;
$index_div = '';
$listnum = 0;
$titl_regex = '~<h([34])>(.+)</h([34])>~'; //匹配两级标题h3和h4
if (preg_match_all($titl_regex, $content, $matches)) { //使用$titl_regex匹配标题
foreach($matches[2] as $num => $title) {
$titlnum = $matches[1][$num];
$title = preg_replace('~<[^>]+>~', '', $title);
if ($titlnum == 4) { //h4标题
$h4num++;
$ul_li. = '<li class="listh4"><a href="#title-'.$num.'" title="'.$title.'"><span class="listnum">'.$h4num.'</span>'.$title.'</a></li>';
} else { //h3标题
$h3num++;
$h4num = 0;
$ul_li. = '<li><a href="#title-'.$num.'" title="'.$title.'"><span class="listnum">'.$h3num.'</span>'.$title.'</a></li>';
}
}
$index_div = '<div id="s1"><h3>文章目录</h3><ul id = "index-ul" >'.$ul_li.'</ul> </div>';
}
echo $index_div;
}
}
function article_titl($content) {
$matches = array();
$titl_regex = "~<h([34])>(.+)</h([34])>~";
if (preg_match_all($titl_regex, $content, $matches)) {
foreach($matches[2] as $num => $title) {
$content = preg_replace('~'.preg_quote($matches[0][$num], '/').'~', '<h'.$matches[1][$num].' id="title-'.$num.'">'.$title.'</h'.$matches[1][$num].'>', $content, 1);
}
}
echo $content;
}
add_filter('the_content', 'article_titl');
使用两级标题h3和h4,对于使用h2和h3,只需将~<h([34])>(.+)</h([34])>~
更改为~<h([23])>(.+)</h([23])>~
,如果使用更多级目录如h2、h3和h4,就需要改成~<h([234])>(.+)</h([234])>~
,对应的if
条件语句增加对h2
的处理即可。
CSS 样式化
CSS样式化要针对网站的实际HTML结构来,下面是本站的相应CSS:
/*目录单行显示*/
#s1 li a {
display:block;
text-overflow:ellipsis;
overflow:hidden;
white-space:pre;
line-height:2
}
/*目录编号样式*/
.listnum {
padding:.0625em .4em;
margin-right:.75em;
font-size:.875em;
background:#bbb;
border-radius:100%;
color:#fff;
transition:.075s
}
#s1 li:hover .listnum {
background:#03A9F4;
transition:.1s
}
/*h4标题目录缩进*/
li.listh4 {
padding-left:2em;
font-size:.85em
}
页面滚动时保持目录固定,参见文章:页面滚动时固定导航菜单或侧边栏。
亦水芙2017 年 09 月 10 日下午 12:12
这个多级目录,编辑文章的时候格式要怎么写呢? 一直无法成功,都是值显示单级目录
snowtraces*2017 年 09 月 11 日上午 11:20
这个是根据标题的标签h2/h3等,文章中有讲啊
亦水芙2017 年 09 月 12 日下午 9:32
我的意思是编辑文章的时候,用标签如何排版才能取得你多级目录有缩进的效果。
比如
目录1是: 目录1
目录1.1如何写?
是紧跟着目录1 输入目录1.1 这样吗?
亦水芙2017 年 09 月 12 日下午 9:35
比如
目录1是: 《h3》目录1《/h3》
目录1.1如何写?
是紧跟着目录1 输入,《h4》目录1.1《/h4》 然后就会自动形成缩进的格式吗?
snowtraces*2017 年 09 月 13 日上午 10:28
对的