<?php
if(!defined('ABSPATH')) exit;

function generate_toc($content) {
    if (is_single()) {
        $toc = '<div class="toc-container"><div class="toc-header">INFORMATION</div><div class="toc-content"><ul>';
        // h2タグを目次の対象とする
        $pattern = '/<h2[^>]*>(.*?)<\/h2>/';
        // h2タグが何個あるかカウント
        $h2_count = preg_match_all($pattern, $content, $h2_matches);

        if ($h2_count >= 2 && preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
            foreach ($matches as $match) {
                $title = $match[1];
                $slug = sanitize_title($title);
                // h2タグに基づいた目次の項目を生成
                $toc .= '<li><span class="toc-text"><a href="#' . $slug . '">' . esc_html($title) . '</a></span></li>';
                // h2タグにIDを追加して目次からリンクできるようにする
                $content = str_replace($match[0], '<h2 id="' . $slug . '">' . $title . '</h2>', $content);
            }

            $toc .= '</ul></div></div>';

            // 目次を最初のh2タグの前に挿入
            $firstHeaderFound = preg_match('/<h2[^>]*>/', $content, $firstMatch);
            if ($firstHeaderFound) {
                $content = preg_replace('/<h2[^>]*>/', $toc . '$0', $content, 1);
            } else {
                $content = $toc . $content; // 見出しがない場合は記事の最初に目次を追加
            }
        }
    }
    return $content;
}
add_filter('the_content', 'generate_toc');

function toc_shortcode($atts, $content = null) {
    if (is_single()) {
        global $post;
        setup_postdata($post);
        $content = apply_filters('the_content', $post->post_content);
        wp_reset_postdata();
        return generate_toc($content);
    }
    return '';
}
add_shortcode('toc', 'toc_shortcode');
?>