@@ -112,38 +112,34 @@ function thp_generate_toc($content) {
112
112
113
113
// To track the nesting level
114
114
$ current_level = 2 ;
115
- $ list_stack = array ();
115
+ $ open_lists = 0 ; // Track the number of open <ul> tags
116
116
117
117
foreach ($ matches [2 ] as $ key => $ heading ) {
118
118
$ heading_level = (int )$ matches [1 ][$ key ];
119
119
$ anchor = sanitize_title ($ heading );
120
120
121
- // Open new lists as needed
122
121
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
+ }
126
127
} 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 ) {
129
129
$ toc .= '</ul> ' ;
130
+ $ open_lists --;
130
131
$ current_level --;
131
- $ toc = array_pop ($ list_stack );
132
132
}
133
133
}
134
134
135
- // Add the list item
136
135
$ toc .= '<li><a href="# ' . $ anchor . '"> ' . $ heading . '</a></li> ' ;
137
-
138
- // Update current level
139
- $ current_level = $ heading_level ;
140
136
$ content = str_replace ($ matches [0 ][$ key ], '<h ' . $ heading_level . ' id=" ' . $ anchor . '"> ' . $ heading . '</h ' . $ heading_level . '> ' , $ content );
141
137
}
142
138
143
139
// Close any remaining open lists
144
- while ($ current_level > 2 ) {
140
+ while ($ open_lists > 0 ) {
145
141
$ toc .= '</ul> ' ;
146
- $ current_level --;
142
+ $ open_lists --;
147
143
}
148
144
149
145
$ toc .= '</ul></aside> ' ;
@@ -177,6 +173,7 @@ function thp_generate_toc($content) {
177
173
178
174
179
175
176
+
180
177
// Add a meta box for hiding a tutorial from general listing
181
178
function thp_add_hide_meta_box () {
182
179
add_meta_box (
0 commit comments