前言
如文章标题所说。这样我们在写文章的时候可以构架好目录,让文章看起来井井有条,特别是在长篇文章的时候效果极佳。
纯代码生成目录PHP部分
这里我们直接修改可以匹配 h2 和 h3 标签,只需要将下面代码加到主题的 functions.php 文件中最后一个”?>”前就可以了。
function article_index($content) { $matches = array(); $ul_li = ''; //匹配出 h2、h3 标题 $rh = "/(.*)<\/h[23]>/im"; $h2_num = 0; $h3_num = 0; //判断是否是文章页 if(is_single()){ if(preg_match_all($rh, $content, $matches)) { // 找到匹配的结果 foreach($matches[1] as $num => $title) { $hx = substr($matches[0][$num], 0, 3); //前缀,判断是 h2 还是 h3 $start = stripos($content, $matches[0][$num]); //匹配每个标题字符串的起始位置 $end = strlen($matches[0][$num]); //匹配每个标题字符串的结束位置 if($hx == " '.$title.'
',$start,$end); $title = preg_replace('/<.+>/', "", $title); //将 h2 里面的 a 链接或者其他标签去除,留下文字 $ul_li .= ''.$title." \n"; }else if($hx == "'.$title.'
',$start,$end); $title = preg_replace('/<.+>/', "", $title); //将 h3 里面的 a 链接或者其他标签去除,留下文字 $ul_li .= ''.$title." \n"; } } } // 将目录拼接到文章 $content = $content . "文章目录"; return $content; }elseif(is_home){ return $content; } } add_filter( "the_content", "article_index" );" . $ul_li . "
纯代码生成目录css部分
.post_nav{position:fixed;top:50%;right:50%;z-index:20;display:block;overflow:hidden;margin-top:-24px;margin-right:620px;width:164px;-webkit-border-radius:2px;-moz-border-radius:2px;-ms-border-radius:2px;-o-border-radius:2px;border-radius:2px;border:1px solid #DEDFE1;background:#fff} .post_title{width:144px;border-bottom:1px dashed #ddd;display:block;line-height:30px;margin-left:10px} .post_nav strong{background:inherit} .post_nav .post_nav_side{position:absolute;top:0;left:5px;width:0;min-height:40px;border:1px solid #eaeaea;border-top:0;border-bottom:0;background-color:#eaeaea} .post_nav .post_nav_content{position:relative;overflow:hidden;overflow-y:scroll;margin:10px 0;padding-left:10px;height:auto;max-height:520px;list-style:none;text-indent:0} .post_nav .post_nav_content li{height:22px;line-height:22px} .post_nav_content li a.tooltip{opacity:100!important} .post_nav .post_nav_content li a{overflow:hidden;height:22px;line-height:25px;max-width:146px;color:#333;vertical-align:top;text-decoration:none;-webkit-text-overflow:ellipsis} @media screen and (max-width:1440px){.post_nav{margin-right:-240px;background:#f7f7f7}
效果直接查看本文章
正文到此结束
版权声明:除非本文有注明出处,否则转载请注明本文来自 https://xwmin.com
QQ游客
支持下…..
cary110
@QQ游客 测试