]*id=["']([^"']*) ["'][^>]*>(.*?)
preg_match_all('/
]*id=["\']([^"\']*)["\'][^>]*>(.*?)<\/h2>/i', $content, $matches);
// Si no hay H2 con ID, no mostrar TOC
if (empty($matches[1])) {
return '';
}
// Iniciar construcción del TOC
$toc = '';
$toc .= '
Tabla de Contenido
';
$toc .= '
';
// Iterar sobre cada H2 encontrado
foreach ($matches[1] as $index => $id) {
// Limpiar el título (eliminar tags HTML internos)
$title = strip_tags($matches[2][$index]);
// Crear el elemento de la lista
$toc .= sprintf(
'- %s
',
esc_attr($id),
esc_html($title)
);
}
$toc .= '
';
$toc .= '
';
return $toc;
}
// Obtener el contenido del post actual
global $post;
$post_content = $post->post_content;
// Aplicar filtros de WordPress al contenido (shortcodes, etc.)
$post_content = apply_filters('the_content', $post_content);
// Generar y mostrar el TOC
echo apu_generate_toc($post_content);