WordPress功能扩展-给文章添加文章索引

本文摘要一:首先在主题函数文件functions.php加入下面代码function article_index($content) { $matches = array(); $ul_li = ''; $r = "/<h3>([^<]+)<\/h3>/im"; if(preg_match_all($r, $content, $matc...

一:首先在主题函数文件functions.php加入下面代码

function article_index($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 class="title-'.$num.'">'.$title.'</h3>', $content);
$ul_li .= '<li><a href="#title-'.$num.'" title="'.$title.'">'.$title."</a></li>\n";
}
$content = "\n<div id=\"article-index\" class=\"article-index hidden-xs\">
<strong class=\"title\">文章目录</strong>
<ul id=\"index-ul\" class=\"index-ul\">\n" . $ul_li . "</ul>
</div>\n" . $content;
}
return $content;
}
add_filter( "the_content", "article_index" );

二:在style.css中加入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;
}

三:如何使用

使用</h3>标签,也就是后台编辑器中的“三级标题”。写文章的时候,为每一个步骤添加一个标题,然后加上<h3/>标签就可以了。如果某篇文章不想用目录索引,那么久不要添加<h3/>标签即可。在这也小小提示下,如果你想优化自己的标题样式,那么修改你主题的样式文件里的h2,而不是h3

觉得内容不错?我要

打赏杯咖啡或蜜雪冰城吧
微信扫一扫
微信赞赏码
支付宝扫一扫
支付宝赞赏码
评论 共2条
面子至上

博主,效果是怎么样的啊 给截个图什么的啊~

gkroot
gkroot LV1

@面子至上 @面子至上 自己动手,丰衣足食