短视频自媒体创业
全国咨询微信:4761160

帝国cms内容正文提取h标签为目录索引方法

发布时间:2020-12-19 09:27:10 人气:

一直想将内容页正文中的h标签提取出来,作为题目使用,就像WordPress里就有这个插件,今天在网上看到有人贴出这段代码,但是不能使用;于是闲下来我就看了一下代码就行修改一下,之前我也是直接使用这段代码但是不行,也就放弃没管,今天突发灵感修改一下,完美实现了。

实现这样为了提升用户体验也同时优化了SEO

首先,在打开帝国cms的e/class/functions.php 文件,在最下面添加以下代码。

//文章目录
function article_index($content) {
  $matches = array();
  $ul_li = '';
  $r = '/<h([2-6]).*?\>(.*?)<\/h[2-6]>/is';
  if(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.'</h'. $value .'>', $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;
}

上传到网站对应的路径下,内容页模板调用:

<?php echo article_index($navinfor[newstext]);?>

保存重新生成一下静态页,看一下是不是出来题目了,下面我给出一个css样式,根据自己需求修改即可:

/*正文标题索引*/
#article-index {
  border-radius: 6px 6px 6px 6px;
  border: 1px solid #DEDFE1;
 
  margin: 0 0 15px 0;
  padding: 0 6px;
 
  line-height: 23px;
}
#article-index strong {
  border-bottom: 1px dashed #DDDDDD;
  display: block;
  line-height: 30px;
  padding: 0 4px;
  color: #DE0208;
}
#index-ul {
  margin: 8px 0px 0px 0px;
  padding-bottom: 10px;
  padding-left: 0px;
}
#index-ul li {
  background: none repeat scroll 0 0 transparent;
  list-style-type: disc;
  padding: 0;
  margin-left: 20px;
}

提取正文H标签目录代码.txt

如果你使用了以前的文章内图片增加alt代码,可以重新在增加赋值再调用一下即可。

替换图片alt代码文章

https://zhanghaiyang.net/news/jishu/106.html

 

在线客服
联系方式

微信号

4761160

上班时间

周一到周五

二维码
线