wordpress内容页如何添加目录(table of content)

Published
2023-08-12
浏览次数 :  35


function generate_table_of_contents($content) {
    if (is_single() && in_the_loop()) {
        preg_match_all('/<h([1-6])>(.*?)<\/h[1-6]>/i', $content, $headings);

        if (!empty($headings[0])) {
            $toc = '<div class="table-of-contents"><h2>Table of Contents</h2><ul>';
            foreach ($headings[0] as $index => $heading) {
                $level = $headings[1][$index];
                $text = strip_tags($headings[2][$index]);
                $id = sanitize_title_with_dashes($text);

                $toc .= '<li><a href="#' . $id . '">' . $text . '</a></li>';

                $content = str_replace($heading, '<h' . $level . ' id="' . $id . '">' . $text . '</h' . $level . '>', $content);
            }
            $toc .= '</ul></div>';
        }

        $content = $toc . $content;
    }

    return $content;
}
add_filter('the_content', 'generate_table_of_contents');

  • 标签1
  • 标签1
  • 标签1
Top