无需插件WordPress内容设置文章索引文章目录标题效果

如果我们在创作文章的时候,这篇文章很长且有很多大标题和小标题,那我们便于阅读效果的体验肯定是需要用到索引目录。这里,我们当然是可以用到WordPress插件实现,比如我们可以用到 LuckyWP Table of Contents、Easy Table of Contents 这两个插件是比较多的。具体的后面麦子再详细介绍这2个插件。

无需插件WordPress内容设置文章索引文章目录标题效果

在这篇文章中,我们不使用插件,直接用代码实现。

1、功能部分

// 无插件文章目录 cnwper.com
function article_index($content) {
$matches = array();
$ul_li = '';
$r = "/([^<]+)</h3>/im";
if(preg_match_all($r, $content, $matches)) {
foreach($matches[1] as $num => $title) {
$content = str_replace($matches[0][$num], ''.$title.'', $content);
$ul_li .= ''.$title."n";
}
$content = "n
文章目录
n" . $ul_li . "
n" . $content;
}
return $content;
}
add_filter( "the_content", "article_index" );

将代码添加到当前主题的 Functions.php 中。

2、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;
}

我们看效果如果感觉不好的再CSS微调。

投票 post
© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享