wordpress主题长内容文章若是有现成的文章目录可以方便读者根据感兴趣的目录的标题来浏览,所以我们如果是经常写超过1千字的wordpress主题内容文章,可以设置一下文章目录索引的功能。即可以实现快速跳转到当前段落的功能。在浏览起来有很好的用户体验提升效果。给文章添加文章目录功能,不仅是文章条理更清楚,还有利于SEO,下面将介绍使用代码来实现文章目录的方法,方便喜欢折腾代码的朋友,如果你不想折腾代码,你可以试试下面的WordPress文章目录插件:TOC 和 Content Index for WordPress。
将下面的代码放到function.php中,就会在你的文章中自动生成一个索引。
//wordpress主题的文章内容添加导航目录
// 文章内容添加文章目录
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>”;
}
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”);
|
注意:须的文章里设置h3的标题标签,
js 代码
在 main.js 中添加以下代码,当点击目录时,能平滑移动到相应的位置,添加了一个样式:smooth
-
//锚点滑动:在href上加上一个样式:smooth
-
$(".smooth").click(function(){
-
var href = $(this).attr("href");
-
var pos = $(href).offset().top-100;
-
$("html,body").animate({scrollTop: pos}, 1000);
-
return false;
-
});
wordpress的文章索引功能是实现了,是通过在文章中的一个普通ul list,我们要做的是把他独立出来,所以只需要为它写一个css样式就好了。推荐用position:fixed把他固定到左边或者右边,下方提供了一个参考样式,可以根据自己的情况去修改。在主题的style.css中填入以下css样式即可:
/*wordpress主题的文章内容添加导航目录效果*/
#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;}