Files
wordpress-theme-aksrt/templates/parts/docs/doc-toc.php
T

42 lines
1.2 KiB
PHP

<?php
/**
* Docs Mode: Table of Contents
*
* 文档模式目录:从文章内容中提取 h2/h3 生成右侧目录。
*
* @package AKSRT
*/
defined('ABSPATH') || exit;
$content = get_the_content();
if (empty($content)) return;
// 提取 h2/h3 标题
$headings = [];
if (preg_match_all('/<h([2-3])[^>]*(?:id="([^"]*)")?[^>]*>(.*?)<\/h\1>/is', $content, $matches, PREG_SET_ORDER)) {
foreach ($matches as $m) {
$level = (int) $m[1];
$id = !empty($m[2]) ? $m[2] : '';
$text = wp_strip_all_tags($m[3]);
if ($text === '') continue;
if ($id === '') {
$id = 'toc-' . sanitize_title($text);
}
$headings[] = ['level' => $level, 'id' => $id, 'text' => $text];
}
}
if (empty($headings)) return;
?>
<nav class="aksrt-doc-toc" aria-label="<?php esc_attr_e('文章目录', 'aksrt'); ?>">
<div class="aksrt-doc-toc__title"><?php esc_html_e('目录', 'aksrt'); ?></div>
<ul class="aksrt-doc-toc__list">
<?php foreach ($headings as $h) : ?>
<li class="aksrt-doc-toc__item aksrt-doc-toc__item--h<?php echo esc_attr((string) $h['level']); ?>">
<a href="#<?php echo esc_attr($h['id']); ?>"><?php echo esc_html($h['text']); ?></a>
</li>
<?php endforeach; ?>
</ul>
</nav>