WordPress 免插件给文章添加文章索引/文章目录

给文章添加文章目录功能,不仅是文章条理更清楚,还有利于SEO,如果你不想折腾代码,你可以试试下面的WordPress文章目录插件:TOC 和 Content Index for WordPress

/**
* Custom WordPress文章索引/文章目录
* @author 无忧网
* @link https://www.wuyouw.com
**/
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" );

述代码添加到主题functions.php文件中最后一个>;之前即可,然后需要在主题style.css文件中添加如下的css样式

<!-- 文章索引开始 -->
<style>
#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;
} 
</style>
<!-- 文章索引结束 -->

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

以上代码的功能比较单一,只有单级目录,不能实现多层级的复杂而完善的索引目录功能。网友12READS对以上代码做了修改,据称可以支持多级目录,暂未测试,需要的可以看看:

/**
* Custom WordPress文章索引/文章目录(支持多层级)
* @author 无忧网
* @link https://www.wuyouw.com
**/
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> <ol id=\"index-ul\">\n" . $ul_li . "</ol> </div>\n" . $content; 
} 
return $content; 
} 
add_filter( 'the_content', 'article_index' );

 

 


给TA打赏
共{{data.count}}人
人已打赏
WordPress教程

WordPress屏蔽所有非中文系语种垃圾评论的方法

2021-10-11 22:31:25

WordPress教程

WordPress文章自动外链go跳转避免权重丢失

2021-10-12 11:44:19

2 条回复 A文章作者 M管理员
  1. 雷死人

    这个外链跳转不错

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索