我正在使用此 PHP 在 WordPress 上生成目录:
add_filter('the_content', function ($content) {
global $tableOfContents;
$tableOfContents = "
<div class='widget widget_toc'>
<h2 class='widgettitle'>Table of Contents <span class='toggle'></span></h2>
<ul>
<li><a href='#preface'>Preface</a></li>
";
$index = 1;
$indexes = [2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0];
// Insert the IDs and create the TOC.
$content = preg_replace_callback('#<(h[1-3])(.*?)>(.*?)</\1>#si', function ($matches) use (&$index, &$tableOfContents, &$indexes) { // H3 Max
$tag = $matches[1];
$title = strip_tags($matches[3]);
$hasId = preg_match('/id=(["\'])(.*?)\1[\s>]/si', $matches[2], $matchedIds);
$id = $hasId ? $matchedIds[2] : $index++ . '-' . sanitize_title($title);
// Generate the prefix based on the heading value.
$prefix = '';
foreach (range(2, $tag[1]) as $i) {
if ($i == $tag[1]) {
$indexes[$i] += 1;
}
$prefix .= $indexes[$i] . '.';
}
$title = "<span class='prefix'>$prefix</span> $title";
$tableOfContents .= "<li class='item-$tag'><a href='#$id'>$title</a></li>";
if ($hasId) {
return $matches[0];
}
return sprintf('<%s%s id="%s">%s</%s>', $tag, $matches[2], $id, $matches[3], $tag);
}, $content);
$tableOfContents .= '</ul></div>';
return $content;
});
function get_the_table_of_contents() {
global $tableOfContents;
return $tableOfContents;
}
function toc_shortcode(){
echo get_the_table_of_contents();
}
add_shortcode('toc', 'toc_shortcode');
我得到的是 4.3 和 4.4 而不是 4.1 和 4.2,因为它们已经在标题 2 中增加了。
如何修改此代码以纠正此问题?