很多网站上在浏览正文的时候旁边有个索引,把每个章节的h3标题列出来,做成锚点,这样可以通过锚点链接快速跳转到相应的章节。
我看了看代码,原理相对简单,首先是利用正则把文章中的h3标签提取出来,然后依次获取h3标签内容,并且给原有的h3标签添加id锚点,然后实现了文章的索引。
把以下代码放到你主题的fuctions.php中
<code>
function article_nav($content)
{
$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], '<h3 id="article_nav_' . $num . '">' . $title . '</h3>', $content);
$ul_li .= '<li><a href="#article_nav_' . $num . '" title="' . $title . '">' . $title . "</a></li>\n";
}
if (is_singular()) {
$content = '<div id="fn_article_nav"><div id="article_nav_title">Article Nav</div><ul>'
. $ul_li . '<li><a href="#respond">发表评论</a></li></ul></div>' . $content;
}
}
return $content;
}
add_filter("the_content", "article_nav");
</code>
function article_nav($content)
{
$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], '<h3 id="article_nav_' . $num . '">' . $title . '</h3>', $content);
$ul_li .= '<li><a href="#article_nav_' . $num . '" title="' . $title . '">' . $title . "</a></li>\n";
}
if (is_singular()) {
$content = '<div id="fn_article_nav"><div id="article_nav_title">Article Nav</div><ul>'
. $ul_li . '<li><a href="#respond">发表评论</a></li></ul></div>' . $content;
}
}
return $content;
}
add_filter("the_content", "article_nav");
</code>
再把以下代码放到你主题的style.css中,不过css部分可以自己写,以下的CSS样式仅供参考。
<code>
#article_nav_title{font-size:11px;text-align:center;line-height:15px;color:#cc0000;border-left:3px #cc0000 solid;border-bottom:1px #aaa dotted}
#fn_article_nav{position:fixed;left:5px;top:140px;background-color:rgba(255,255,255,.55);border-radius: 0 3px 3px 0;box-shadow:0 0 2px #aaa}
#fn_article_nav ul{padding:0!important;margin:0px!important}
#fn_article_nav li{list-style:none;padding:3px;width:100px;margin:0;background: url("images/li.png") no-repeat scroll 0 5px transparent!important;text-indent: 1.6em;}
</code>
#article_nav_title{font-size:11px;text-align:center;line-height:15px;color:#cc0000;border-left:3px #cc0000 solid;border-bottom:1px #aaa dotted}
#fn_article_nav{position:fixed;left:5px;top:140px;background-color:rgba(255,255,255,.55);border-radius: 0 3px 3px 0;box-shadow:0 0 2px #aaa}
#fn_article_nav ul{padding:0!important;margin:0px!important}
#fn_article_nav li{list-style:none;padding:3px;width:100px;margin:0;background: url("images/li.png") no-repeat scroll 0 5px transparent!important;text-indent: 1.6em;}
</code>