使用純代碼給WordPress添加文章目錄功能,支持快速定位和多級目錄

wordpress是一款強大的博客系統,支持各種DIY,今天我就給大家帶來使用純代碼給Wordpress添加文章目錄的功能,使看文章更簡單!并且支持點擊目錄標題快速定位到文章頁面指定內容點。

一、文章目錄代碼

把以下代碼添加到主題的Functions.php文件中

//國外主機測評-www.lrracing.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>
<ul id=\"index-ul\">\n" . $ul_li . "</ul>
</div>\n" . $content;
}
return $content;
}
add_filter( 'the_content', 'article_index' );

二、CSS樣式代碼

把以下代碼添加到主題的“main.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;
}

三、最終效果

贊(0)
版權聲明:本文采用知識共享 署名4.0國際許可協議 [BY-NC-SA] 進行授權, 轉載請注明出處。
文章名稱:《使用純代碼給WordPress添加文章目錄功能,支持快速定位和多級目錄》
文章鏈接:http://www.lrracing.com/12312.html
【聲明】:國外主機測評僅分享信息,不參與任何交易,也非中介,所有內容僅代表個人觀點,均不作直接、間接、法定、約定的保證,讀者購買風險自擔。一旦您訪問國外主機測評,即表示您已經知曉并接受了此聲明通告。
【關于安全】:任何 IDC商家都有倒閉和跑路的可能,備份永遠是最佳選擇,服務器也是機器,不勤備份是對自己極不負責的表現,請保持良好的備份習慣。