給文章添加文章目錄功能,不僅是文章條理更清楚,還有利于SEO,下面將介紹 露兜 老大的使用代碼來實(shí)現(xiàn)文章目錄的方法,方便喜歡折騰代碼的朋友,如果你不想折騰代碼,你可以試試下面的WordPress文章目錄插件:TOC 和 Content Index for WordPress。
用代碼實(shí)現(xiàn)文章目錄
1.將下面的代碼添加到主題的 functions.php 文件的 最后一個(gè) ?> 前面:
function article_index($content) {
/**
* 名稱:文章目錄插件
* 作者:露兜
* 博客:http://www.ludou.org/
* 最后修改:2011年2月10日
*/
$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 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" );
使用說明
在編輯文章的時(shí)候,在可視化模式下,選中文字,設(shè)置為標(biāo)題3(H3),或者切換到HTML模式,將需要添加到目錄中的標(biāo)題用<h3>和</h3>括起來就可以了,如<h3>我是索引標(biāo)題</h3>。當(dāng)然你也可以用其他標(biāo)簽,如<h2>,<p>等,將以上代碼第12行中的h3改成你自己的標(biāo)簽名稱就可以了。
CSS樣式參考
為了實(shí)現(xiàn)前臺(tái)的顯示效果,你可以參考下面的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;
}
以上代碼的功能比較單一,只有單級目錄,不能實(shí)現(xiàn)多層級的復(fù)雜而完善的索引目錄功能,如果你需要這些功能,那你就要借助文章目錄插件:TOC 和 Content Index for WordPress。





怎么設(shè)置成百度百科那樣的目錄導(dǎo)航啊
請問怎樣能把目錄做成您的網(wǎng)站這個(gè)樣子?我的目錄總會(huì)把文字?jǐn)D開,占據(jù)整行空間,我想讓文字目錄環(huán)繞目錄(大概就這么形容吧) http://www.lizhuo93.cn
插件有設(shè)置選項(xiàng)的,你自己看看
能不能讓這歌功能加載到指定位置呢?如果能,怎么加,貼代碼
這個(gè)功能還是比較弱。
博主,這個(gè)函數(shù)顯示的文章評論數(shù)量<?php comments_popup_link (‘0°’,’+1°’,’+%°’); ?>,
但它是以超鏈接的形式出現(xiàn)的,如何讓它以純文本的形式打印出來?
先折騰下
博主使用的是Content Index for WordPress嗎