Skip to content

Commit 0956558

Browse files
authored
Update tuts.php
fixed bug where when using h3 headlines and then using h2 headlines again the toc wouldnt show the h3 headlines anymore
1 parent 9a10e3c commit 0956558

File tree

1 file changed

+11
-14
lines changed

1 file changed

+11
-14
lines changed

tuts.php

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -112,38 +112,34 @@ function thp_generate_toc($content) {
112112

113113
// To track the nesting level
114114
$current_level = 2;
115-
$list_stack = array();
115+
$open_lists = 0; // Track the number of open <ul> tags
116116

117117
foreach ($matches[2] as $key => $heading) {
118118
$heading_level = (int)$matches[1][$key];
119119
$anchor = sanitize_title($heading);
120120

121-
// Open new lists as needed
122121
if ($heading_level > $current_level) {
123-
// Push current list onto stack
124-
$list_stack[] = $toc;
125-
$toc .= '<ul>';
122+
while ($heading_level > $current_level) {
123+
$toc .= '<ul>';
124+
$open_lists++;
125+
$current_level++;
126+
}
126127
} elseif ($heading_level < $current_level) {
127-
// Close lists as needed
128-
while ($heading_level < $current_level) {
128+
while ($heading_level < $current_level && $open_lists > 0) {
129129
$toc .= '</ul>';
130+
$open_lists--;
130131
$current_level--;
131-
$toc = array_pop($list_stack);
132132
}
133133
}
134134

135-
// Add the list item
136135
$toc .= '<li><a href="#' . $anchor . '">' . $heading . '</a></li>';
137-
138-
// Update current level
139-
$current_level = $heading_level;
140136
$content = str_replace($matches[0][$key], '<h' . $heading_level . ' id="' . $anchor . '">' . $heading . '</h' . $heading_level . '>', $content);
141137
}
142138

143139
// Close any remaining open lists
144-
while ($current_level > 2) {
140+
while ($open_lists > 0) {
145141
$toc .= '</ul>';
146-
$current_level--;
142+
$open_lists--;
147143
}
148144

149145
$toc .= '</ul></aside>';
@@ -177,6 +173,7 @@ function thp_generate_toc($content) {
177173

178174

179175

176+
180177
// Add a meta box for hiding a tutorial from general listing
181178
function thp_add_hide_meta_box() {
182179
add_meta_box(

0 commit comments

Comments
 (0)