小冬SEO

wordpress获取文章小标题做目录

2021-11-06 22:13:43 5797 WordPress笔记

wordpress获取文章小标题做目录,包含h2、h3等,实现方法如下。

方法一:获取文章小标题做目录

在主题的functions.php函数中添加如下代码

//文章目录获取
function article_index($content) {
    $matches = array();
    $ul_li = '';
    //匹配出h2、h3标题
    $rh = "/<h[23]>(.*?)<\/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 == "<h2"){
                    $h2_num += 1; //记录h2的序列,此效果请查看百度百科中的序号,如1.1、1.2中的第一位数
                    $h3_num = 0;
                    // 文章标题添加id,便于目录导航的点击定位
                    $content = substr_replace($content, '<h2 id="h2-'.$num.'">'.$title.'</h2>',$start,$end);
                    $title = preg_replace('/<.+?>/', "", $title); //将h2里面的a链接或者其他标签去除,留下文字
                    $ul_li .= '<li class="h2_nav"><a href="#h2-'.$num.'" class="tooltip" title="'.$title.'">'.$title."</a><i class=\"post_nav_dot\"></i></li>\n";
                }else if($hx == "<h3"){
                    $h3_num += 1; //记录h3的序列,此熬过请查看百度百科中的序号,如1.1、1.2中的第二位数
                    $content = substr_replace($content, '<h3 id="h3-'.$num.'">'.$title.'</h3>',$start,$end);
                    $title = preg_replace('/<.+?>/', "", $title); //将h3里面的a链接或者其他标签去除,留下文字
                    $ul_li .= '<li class="h3_nav"><a href="#h3-'.$num.'" class="tooltip" title="'.$title.'">'.$title."</a><i class=\"post_nav_dot\"></i></li>\n";
                }  
            }
        }
        // 将目录拼接到文章
        $content = "<div class=\"post_nav\"><ul class=\"post_nav_content\">\n" . $ul_li . "</ul></div>\n" . $content;//$content放在前面目录就在文章后面,位置可调!
        return $content;
    }elseif(is_home){
        return $content;
    }
}
add_filter( "the_content", "article_index" );

方法二:获取文章小标题做目录

在主题的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 class="nav-' . $value . '"><a href="#title-'.$key.'" title="'.$title.'">'.$title."</a></li>\n";
}
$content = "\n<div id=\"dw__toc\">
<h3>目录</h3>
<ul id=\"index-ul\">\n" . $ul_li . "</ul>
</div>\n" . $content;
}
return $content;
}
add_filter( 'the_content', 'article_index' );

调用代码说明

<?php the_content(); ?><!--通过文章内容直接调用-->

版权保护: 本文由小冬SEO编辑发布,转载请保留链接: http://www.myseoyh.cn/shuo/126.html