wordpress主题开发-非插件给文章添加文章索引/文章目录

在进行wordpress主题开发的过程中,给文章页面添加文章目录功能,不仅是文章条理更清楚,还有利于搜索引擎蜘蛛的爬取,也就是平常所说的SEO.
下面提供以代码的方式给文章添加文章目录,方便喜欢wordpress主题二次开发的朋友,如果你不想折腾代码,你可以试试下面的WordPress文章目录插件:TOC 和 Content Index for WordPress

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" );

CSS代码

主题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;
}

使用说明

在编辑文章的时候,将索引部分设置为3 级标题

代码自定义

你也可以设置为 2 级标题,此时需要将功能代码中的所有的h3改为h2。

如何获得最好的网站定制服务?wordpress公园,争做中国最专业的web app开发商

0

wordpress公园

星辉科技旗下产品,让wordpress更好的在中国本土化!

发表评论

电子邮件地址不会被公开。 必填项已用*标注

微信扫一扫

微信扫一扫

微信扫一扫,分享到朋友圈

wordpress主题开发-非插件给文章添加文章索引/文章目录
嘿!有什么能帮到您的吗?
返回顶部

显示

忘记密码?

显示

显示

获取验证码

密码找回

获取验证码

显示

返回登陆

Close