1. <?php
    2. function ribs_article_nav($content) {
    3. $matches = array();
    4. $ul_li = '';
    5. $respond = '';
    6. $h2 = "/<h2>(.*?)<\/h2>/im";
    7. $h3 = "/<h3>(.*?)<\/h3>/im";
    8. if (preg_match_all($h3, $content, $matches)) {
    9. foreach ($matches[1] as $num => $title) {
    10. $content = str_replace($matches[0][$num], '<h3 id="article_nav_h3_' . $num . '">' . $title . '</h3>', $content);
    11. $ul_li.= '<li><a href="#article_nav_h3_' . $num . '" title="' . $title . '">' . $title . "</a></li>";
    12. }
    13. if (comments_open() || get_comments_number()) {
    14. $respond = '<li><a href="#respond">发表评论</a></li>';
    15. }
    16. if (is_singular()) {
    17. $content = '<div id="ribs_article_nav" class="p-3 border"><div id="article_nav_title">文章大纲</div><ul>' . $ul_li . $respond . '</ul></div>' . $content;
    18. }
    19. }
    20. return $content;
    21. }
    22. add_filter("the_content", "ribs_article_nav");