WordPress 文章目录免插件代码方法
现在网站开始流行给页面添加目录,方便访客浏览,其实维基百科很早就在使用。WordPress平台文章目录的生成方式有很多,省事就是直接使用插件,但几个经典插件久未更新,而且多在文章内展示。百度搜了下找到下面的免插件代码方法,完成后文章目录放在侧边栏,会随着页面滚动保持跟随。
PHP 代码
- //文章目录
- function article_index() {
- if (is_singular()) //判断文章页
- {
- global $post;
- $matches = array();
- $ul_li = '';
- $content = $post - > post_content;
- $index_div = '';
- $listnum = 0;
- $titl_regex = '~<h([34])>(.+)</h([34])>~'; //匹配两级标题h3和h4
- if (preg_match_all($titl_regex, $content, $matches)) { //使用$titl_regex匹配标题
- foreach($matches[2] as $num => $title) {
- $titlnum = $matches[1][$num];
- $title = preg_replace('~<[^>]+>~', '', $title);
- if ($titlnum == 4) { //h4标题
- $h4num++;
- $ul_li. = '<li class="listh4"><a href="#title-'.$num.'" title="'.$title.'"><span class="listnum">'.$h4num.'</span>'.$title.'</a></li>';
- } else { //h3标题
- $h3num++;
- $h4num = 0;
- $ul_li. = '<li><a href="#title-'.$num.'" title="'.$title.'"><span class="listnum">'.$h3num.'</span>'.$title.'</a></li>';
- }
- }
- $index_div = '<div id="s1"><h3>文章目录</h3><ul id = "index-ul" >'.$ul_li.'</ul> </div>';
- }
- echo $index_div;
- }
- }
- function article_titl($content) {
- $matches = array();
- $titl_regex = "~<h([34])>(.+)</h([34])>~";
- if (preg_match_all($titl_regex, $content, $matches)) {
- foreach($matches[2] as $num => $title) {
- $content = preg_replace('~'.preg_quote($matches[0][$num], '/').'~', '<h'.$matches[1][$num].' id="title-'.$num.'">'.$title.'</h'.$matches[1][$num].'>', $content, 1);
- }
- }
- echo $content;
- }
- add_filter('the_content', 'article_titl');
使用两级标题h3和h4,对于使用h2和h3,只需将~<h([34])>(.+)</h([34])>~
更改为~<h([23])>(.+)</h([23])>~
,如果使用更多级目录如h2、h3和h4,就需要改成~<h([234])>(.+)</h([234])>~
,对应的if
条件语句增加对h2
的处理即可。
CSS 样式化
CSS样式化要针对网站的实际HTML结构来,下面是本站的相应CSS:
- /*目录单行显示*/
- #s1 li a {
- display:block;
- text-overflow:ellipsis;
- overflow:hidden;
- white-space:pre;
- line-height:2
- }
- /*目录编号样式*/
- .listnum {
- padding:.0625em .4em;
- margin-right:.75em;
- font-size:.875em;
- background:#bbb;
- border-radius:100%;
- color:#fff;
- transition:.075s
- }
- #s1 li:hover .listnum {
- background:#03A9F4;
- transition:.1s
- }
- /*h4标题目录缩进*/
- li.listh4 {
- padding-left:2em;
- font-size:.85em
- }
代码来自https://xinyo.org/archives/65879#s1
效果如图
共有 0 条评论