相信大家再写博文过程中,如果一遍文章内容比较多的时候希望通过文章头部的目录导航来让读者清新知道文章讲述的内容,及内容包含的各个模块。今天歪迪wordpress建站网就为大家介绍如何使用代码集成文章目录功能。
免插件实现方法
其实现这样的一个功能还是比较简单的,也就是在文章内容中插进标题标签,然后弄成目录就是了,下面是我写的一个简单的代码,用文本编辑器打开当前主题目录下的functions.php,将以下代码放到 <?php 下面就可以(记得用UTF-8编码保存,否则中文会乱码):
function article_index($content) { /** * 文章目录代码版 * http://www.53431.com/wordpress-directories-Code-version.html */ $matches = array(); $ul_li = ''; $r = "/<h3>([^<]+)</h3>/im"; if(is_singular() && preg_match_all($r, $content, $matches)) { foreach($matches[1] as $num => $title) { $title = trim(strip_tags($title)); $content = str_replace($matches[0][$num], '<h3 id="title-'.$num.'">'.$title.'</h3>', $content); $ul_li .= '<li><a href="#title-'.$num.'" 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' );
多级显示
如果你要多级显示,可以使用一下代码:
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' );
我下面的样式放在你的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; }
使用说明
在编辑文章的时候,切换到HTML模式,将需要添加到目录中的标题用<h3>
和</h3>
括起来就可以了,如<h3>我是索引标题</h3>
。当然你也可以用其他标签,如<h1>
,<p>
等,将以上代码第12和17行中的h3改成你自己的标签名称就可以了。
功能更强大的文章目录插件
如果你需要这些功能可以试试这以下这几个插件,使用也都比较简单:
- Content Index for WordPress
- jQuery Table of Contents
- WP-TOC 激活该插件后,在文章中插入[toc depth="2"]即可,2表示h2、h3、h4...等都会被插进目录,类推[toc depth="3"]则表示h3、h4...等都会被插进目录
评论前必须登录!
注册