提示:如果官网是英文页面,建议使用谷歌浏览器能同步翻译页面。 商家软文投稿QQ2865037586
WordPress作为一款强大的博客程序,深受广大站长的喜欢,尤其如今织梦开始收费,很多站长把目光投向了WordPress。在平时的写作中由于篇幅很长,造成读者阅读不是很方便,那是否可以设置锚点来为文章做个目录引导呢?这个当然是可以,今天小牛就为大家介绍不使用插件,直接添加两行代码就可以实现!
一、锚点代码
//文章目录
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' );
二、CSS样式代码
然后再在主题的“main.css”文件中添加下面样式代码
#article-index {
-moz-border-radius: 6px 6px 6px 6px;
border: 1px solid #DEDFE1;
float: right;
margin: 0 0 15px 15px;
padding: 0 6px;
width: 200px;
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;
}
评论前必须登录!
注册