使用纯代码给WordPress添加文章目录功能,支持快速定位和多级目录
由
Deepseek提供支持
广告
wordpress是一款强大的博客系统,支持各种DIY,今天我就给大家带来使用纯代码给Wordpress添加文章目录的功能,使看文章更简单!并且支持点击目录标题快速定位到文章页面指定内容点。
一、文章目录代码
把以下代码添加到主题的Functions.php文件中
//文章目录
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;
}
温馨提示 : 非特殊注明,否则均为©李联华的博客网原创文章,本站文章未经授权禁止任何形式转载;来自:俄亥俄州·哥伦布 ,欢迎您的访问!
文章链接:https://www.lilianhua.com/use-pure-code-to-add-article-directory-function-to-wordpress-and-support-rapid-positioning-and-multi-level-directory.html
文章链接:https://www.lilianhua.com/use-pure-code-to-add-article-directory-function-to-wordpress-and-support-rapid-positioning-and-multi-level-directory.html
English (US)
Español (ES)
Português (PT)
Français (CA)
Español (MX)
Español (VE)
Español (CO)
Español (AR)
Português (BR)
Quechua (PE)
Guaraní (PY)
简体中文 (ZH)
繁體中文 (HK)
日本語 (JP)
한국어 (KR)
हिन्दी (HI)
Pilipino (PH)
ไทย (TH)
Tiếng Việt (VN)
Bahasa Melayu (MY)
Bahasa Indonesia (ID)
বাংলা (BD)
اردو (PK)
සිංහල (LK)
ភាសាខ្មែរ (KH)
English (UK)
Français (FR)
Deutsch (DE)
Italiano (IT)
Русский (RU)
Nederlands (NL)
Türkçe (TR)
Polski (PL)
Svenska (SE)
Norsk (NO)
Dansk (DK)
Suomi (FI)
Ελληνικά (GR)
Čeština (CZ)
Magyar (HU)
Română (RO)
Български (BG)
Српски (RS)
Українська (UA)

