-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic-toc.php
More file actions
867 lines (779 loc) · 28.7 KB
/
dynamic-toc.php
File metadata and controls
867 lines (779 loc) · 28.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
<?php
/**
* Dynamic Table of Contents Generator
*
* @package Dynamic_TOC
* @author Nathan Johnson
* @copyright 2025 Nathan Johnson
* @license GPL-2.0-or-later
*
* @wordpress-plugin
* Plugin Name: Dynamic Table of Contents Generator
* Plugin URI: https://github.com/NathanDozen3/dynamic-toc/
* Description: Automatically generates a dynamic table of contents for posts and pages based on headings.
* Version: 1.6.4
* Requires at least: 5.2
* Requires PHP: 8.1
* Author: Nathan Johnson
* Author URI: https://github.com/NathanDozen3
* Text Domain: ttm-dynamic-toc
* License: GPL v2 or later
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
*/
declare( strict_types=1 );
namespace TTM\Dynamic_TOC;
use WP_Post;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Define plugin version constant.
*/
add_action(
'init',
function () {
$plugin_version = get_plugin_data( __FILE__ )['Version'];
define( 'TTM_DYNAMIC_TOC_VERSION', $plugin_version );
}
);
/**
* Load textdomain for translations
*/
add_action(
'plugins_loaded',
function () {
load_plugin_textdomain( 'dynamic-toc', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
);
/**
* Get the list of post types that support the TOC meta box.
*
* @since 1.5
* @return string[] Array of post type slugs.
*/
function ttm_get_meta_post_types(): array {
/**
* Filter the list of post types which should display the Dynamic TOC meta box.
*
* Allows themes and plugins to add support for additional post types.
*
* @since 1.1
*
* @param string[] $post_types Array of post type slugs. Default: array( 'post', 'page' ).
* @return string[]
*/
$post_types = apply_filters( 'ttm_dynamic_toc_meta_post_types', array( 'post', 'page' ) );
// Ensure we are working with an array for safety.
if ( ! is_array( $post_types ) ) {
$post_types = [];
}
$post_types = array_filter(
$post_types,
/**
* Ensures the post type slug is a valid string and exists in the WordPress installation.
*
* @param mixed $pt The potential post type slug.
* @return bool True if the post type is a valid, existing string slug.
*/
static function ( $pt ): bool {
return is_string( $pt ) && post_type_exists( $pt );
}
);
// Cast to array ensures the return type matches the function signature, even if the result is empty.
return (array) $post_types;
}
/**
* Get the post meta key used for per-post TOC enable flag.
*
* @since 1.5
* @return string Meta key name.
*/
function ttm_get_dynamic_toc_meta_key(): string {
/**
* Filter the post meta key used to determine whether the TOC is enabled per-post.
*
* Allows changing the meta key name that the plugin looks up on the post.
*
* @since 1.1
*
* @param string $meta_key Meta key to check for per-post TOC enable. Default 'ttm_dynamic_toc_enabled'.
* @param int $post_id Post ID.
* @return string
*/
$post_id = get_the_ID();
$meta_key = apply_filters( 'ttm_dynamic_toc_meta_key', 'ttm_dynamic_toc_enabled', $post_id );
if ( $post_id ) {
/**
* Filters the post meta key used to determine whether the TOC is enabled for a specific post.
*
* This is a dynamic hook, the actual hook name includes the post ID. Example:
* `ttm_dynamic_toc_meta_key_123` for post ID 123.
*
* @since 1.5
*
* @param string $meta_key Meta key to check for per-post TOC enable. Default: 'ttm_dynamic_toc_enabled'.
* @param int $post_id Post ID.
* @return string Filtered meta key to use for this post.
*/
$meta_key = apply_filters( "ttm_dynamic_toc_meta_key_$post_id", $meta_key, $post_id );
}
return $meta_key;
}
/**
* Register plugin assets (scripts & styles).
*
* Registers the script and style handles so they may be enqueued when a TOC is rendered.
*
* @since 1.1
* @return void
*/
function ttm_dynamic_toc_register_assets(): void {
wp_register_script( 'ttm-dynamic-toc', plugin_dir_url( __FILE__ ) . 'js/dynamic-toc.js', array(), TTM_DYNAMIC_TOC_VERSION, true );
wp_register_style( 'ttm-dynamic-toc', plugin_dir_url( __FILE__ ) . 'css/dynamic-toc.css', array(), TTM_DYNAMIC_TOC_VERSION );
}
add_action( 'wp_enqueue_scripts', __NAMESPACE__ . '\\ttm_dynamic_toc_register_assets' );
/**
* Register the Gutenberg block for inserting the Dynamic TOC.
*
* Registers the dynamic TOC block using the block.json metadata file, allowing
* editors to insert a [dynamic_toc] shortcode via the block editor UI.
*
* @since 1.5.0
* @return void
*/
function ttm_dynamic_toc_register_block(): void {
// Ensure block.json exists before attempting to register.
$block_json_file = plugin_dir_path( __FILE__ ) . 'blocks/dynamic-toc-block/block.json';
if ( ! file_exists( $block_json_file ) ) {
return;
}
// Register the block via block.json metadata.
register_block_type( $block_json_file );
// Enqueue the compiled editor script from the block's build/ directory.
$build_file = plugin_dir_path( __FILE__ ) . 'blocks/dynamic-toc-block/build/index.js';
if ( file_exists( $build_file ) ) {
wp_enqueue_script(
'ttm-dynamic-toc-block-editor',
plugin_dir_url( __FILE__ ) . 'blocks/dynamic-toc-block/build/index.js',
array( 'wp-blocks', 'wp-block-editor', 'wp-i18n' ),
filemtime( $build_file ),
true
);
}
}
add_action( 'init', __NAMESPACE__ . '\\ttm_dynamic_toc_register_block' );
/**
* Filter the post content and inject the dynamic TOC when enabled.
*
* Determines whether the TOC is enabled for the current post (per-post meta takes precedence
* over the global option) and delegates to {@see automatic_toc()} when enabled.
*
* @since 1.1
* @param string $content Post content.
* @return string Modified content with TOC when applicable.
*/
function ttm_dynamic_toc_the_content( string $content ): string {
// Only run on front-end singular pages in the main query.
if ( is_admin() || ! is_singular() ) {
return $content;
}
global $post;
// Per-page meta takes precedence. If post meta is explicitly set (0/1), use it.
// Fallback to global option and then filter.
$meta_key = ttm_get_dynamic_toc_meta_key();
$meta_val = get_post_meta( isset( $post->ID ) ? (int) $post->ID : 0, $meta_key, true );
if ( '' !== $meta_val && null !== $meta_val ) {
$enabled = (bool) $meta_val;
} else {
// Read enable flag from an option (remove ACF dependency). Site owners can set this option.
// Or filter it programmatically. Default: false.
$enabled = (bool) get_option( 'ttm_dynamic_toc_enabled', false );
}
$post_id = isset( $post->ID ) ? (int) $post->ID : 0;
// Use the raw post content (blocks/shortcodes) to detect whether the
// TOC block/shortcode was inserted. If so, render the post HTML and
// replace the shortcode with the TOC while still applying IDs.
$raw = get_post_field( 'post_content', $post_id );
$has_short = function_exists( 'has_shortcode' ) && is_string( $raw ) && has_shortcode( $raw, 'dynamic_toc' );
$has_block = function_exists( 'has_block' ) && is_string( $raw ) && has_block( 'ttm/dynamic-toc', $raw );
// Allow programmatic overrides.
/**
* Filter whether the dynamic TOC is enabled for a given post.
*
* This filter receives the current enabled state and the post ID so callers
* can enable or disable the TOC programmatically.
*
* @since 1.1
*
* @param bool $enabled Current enabled state.
* @param int $post_id Post ID being checked.
* @return bool
*/
$enabled = apply_filters( 'ttm_dynamic_toc_enabled', $enabled, isset( $post->ID ) ? $post->ID : 0 );
if ( ! $has_block && ! $enabled ) {
return $content;
}
if ( $has_short || $has_block ) {
// Render blocks and shortcodes to get the actual HTML that will be
// output on the frontend, then run automatic_toc on that HTML.
$rendered = is_string( $raw ) ? $raw : $content;
if ( function_exists( 'do_blocks' ) ) {
$rendered = do_blocks( $rendered );
}
if ( function_exists( 'do_shortcode' ) ) {
$rendered = do_shortcode( $rendered );
}
$toc_html = automatic_toc( $rendered, $post_id, 'toc' );
$content_only = automatic_toc( $rendered, $post_id, 'content' );
// Replace shortcode token with the generated TOC and return.
return str_replace( '[dynamic_toc]', $toc_html, $content_only );
}
return automatic_toc( $content, $post_id, 'both' );
}
add_filter( 'the_content', __NAMESPACE__ . '\ttm_dynamic_toc_the_content' );
/**
* Build and inject the TOC into post content.
*
* Parses configured heading levels, generates/ensures unique IDs, builds the TOC HTML,
* enqueues required assets, and caches the final output in a per-post transient.
*
* @since 1.1
* @param string $content Post content HTML.
* @param int $post_id Post ID.
* @param string $output Output mode: 'both' (default, TOC + content), 'toc' (only TOC HTML), 'content' (only modified content).
* @return string Content prefixed with TOC HTML when headings found; original content otherwise.
*/
function automatic_toc( string $content, int $post_id = 0, string $output = 'both' ): string {
// Build TOC using DOMDocument to be more reliable than regex.
$toc_list = array();
// Suppress libxml warnings for malformed HTML fragments.
$internal_errors = libxml_use_internal_errors( true );
// Validate output mode: 'both' (default), 'toc' (only TOC HTML), 'content' (only modified content).
$allowed_outputs = array( 'both', 'toc', 'content' );
if ( ! in_array( $output, $allowed_outputs, true ) ) {
$output = 'both';
}
$doc = new \DOMDocument();
// Wrap content in a container so we can extract modified inner HTML later.
$wrapped = '<div class="ttm-toc-wrapper">' . $content . '</div>';
/*
* Avoid deprecated mb_convert_encoding() handling of HTML entities. Prepending an
* XML encoding declaration and using LIBXML flags produces consistent results
* with DOMDocument::loadHTML without triggering mbstring deprecation notices.
*/
$html_for_dom = '<?xml encoding="utf-8" ?>' . $wrapped;
// LIBXML_HTML_NOIMPLIED and LIBXML_HTML_NODEFDTD keep DOMDocument from adding
// extra html/body tags around fragments on newer PHP versions.
$doc->loadHTML( $html_for_dom, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
$xpath = new \DOMXPath( $doc );
// Allow configurable heading levels (defaults to h2-h4).
$default_levels = array( 2, 3, 4 );
/**
* Filter the heading levels that the TOC should include.
*
* Receives an array of integers representing heading levels (1-6). Default is h2-h4.
*
* @since 1.1
*
* @param int[] $levels Array of heading levels to include. Default: array(2,3,4).
* @return int[]
*/
$levels = (array) apply_filters( 'ttm_dynamic_toc_heading_levels', $default_levels );
$tags = array();
foreach ( $levels as $lvl ) {
$lvl = (int) $lvl;
if ( $lvl >= 1 && $lvl <= 6 ) {
$tags[] = 'h' . $lvl;
}
}
if ( empty( $tags ) ) {
// Fallback to h2 if configuration is empty/invalid.
$tags = array( 'h2' );
}
// Build xpath query to select all requested heading tags in document order.
$xpath_query_parts = array();
foreach ( $tags as $tag ) {
$xpath_query_parts[] = '//' . $tag;
}
$xpath_query = implode( '|', $xpath_query_parts );
// Identify any heading nodes inside custom_block containers and mark them to ignore.
$ignore_map = array();
$custom_divs = $xpath->query( '//div[contains(concat(" ", normalize-space(@class), " "), " custom_block ")]' );
foreach ( $custom_divs as $div ) {
$inner_nodes = $xpath->query( '.' . str_replace( '//', '/', $xpath_query ), $div );
foreach ( $inner_nodes as $n ) {
$ignore_map[ spl_object_hash( $n ) ] = true;
}
}
// phpcs:disable Squiz.NamingConventions.ValidVariableName.NotSnakeCase
// Gather all heading nodes.
$nodes = $xpath->query( $xpath_query );
$used_slugs = array();
foreach ( $nodes as $node ) {
// Skip any headings inside ignored containers.
if ( isset( $ignore_map[ spl_object_hash( $node ) ] ) ) {
continue;
}
$heading_text = trim( $node->textContent ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
if ( '' === $heading_text ) {
continue;
}
// Use existing ID if present; otherwise generate a safe WP slug and ensure uniqueness.
if ( $node->hasAttribute( 'id' ) ) {
$slug = $node->getAttribute( 'id' );
} else {
$slug = \sanitize_title( wp_strip_all_tags( $heading_text ) );
$original = $slug;
$i = 2;
while ( in_array( $slug, $used_slugs, true ) ) {
$slug = $original . '-' . $i;
$i++;
}
$node->setAttribute( 'id', $slug );
}
$used_slugs[] = $slug;
// Determine heading level (e.g., h2 -> 2). Default to 2 if not parsable.
$tag_name = strtolower( $node->nodeName ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$level = 2;
if ( 0 === strpos( $tag_name, 'h' ) && isset( $tag_name[1] ) ) {
$maybe = (int) substr( $tag_name, 1 );
if ( $maybe >= 1 && $maybe <= 6 ) {
$level = $maybe;
}
}
$toc_list[] = array(
'slug' => $slug,
'text' => $heading_text,
'level' => $level,
);
}
// Restore libxml state.
libxml_clear_errors();
libxml_use_internal_errors( $internal_errors );
// Nothing to do if no headings found.
if ( empty( $toc_list ) ) {
return $content;
}
// Enqueue assets only when we will output the TOC (or when caller
// explicitly asked for only the content but the original content
// already contains a TOC). We can't know that yet, so enqueue when
// output isn't 'content'.
if ( 'content' !== $output && ! is_admin() ) {
wp_enqueue_script( 'ttm-dynamic-toc' );
wp_enqueue_style( 'ttm-dynamic-toc' );
}
// Build output and support server-side caching. Use a single per-post transient that
// stores both the content hash and the HTML so we can invalidate easily on save.
/**
* Filter the per-post TOC cache TTL (seconds).
*
* Allows adjustment of how long the server-side per-post TOC transient is cached.
*
* @since 1.1
*
* @param int $ttl Time to live in seconds. Default: 12 * HOUR_IN_SECONDS.
* @return int
*/
$cache_ttl = (int) apply_filters( 'ttm_dynamic_toc_cache_ttl', 12 * HOUR_IN_SECONDS );
$cache_key = 'ttm_toc_' . (int) $post_id . '_' . $output;
$cached = get_transient( $cache_key );
$content_hash = md5( $content );
if ( is_array( $cached ) && isset( $cached['hash'], $cached['html'] ) && $cached['hash'] === $content_hash ) {
return $cached['html'];
}
// Extract the modified inner HTML of our wrapper container.
$wrapper = $doc->getElementsByTagName( 'div' )->item( 0 );
$new_content = '';
if ( $wrapper ) {
foreach ( $wrapper->childNodes as $child ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$new_content .= $doc->saveHTML( $child );
}
} else {
// Fallback.
$new_content = $content;
}
// phpcs:enable Squiz.NamingConventions.ValidVariableName.NotSnakeCase
// Build TOC HTML and allow developers to filter it.
$toc_html = toc( $toc_list );
/**
* Filter the generated TOC HTML before it is inserted into the post content.
*
* This filter allows plugins or themes to modify the rendered TOC markup, or
* replace it entirely.
*
* @since 1.1
*
* @param string $toc_html Rendered TOC HTML.
* @param array<int,array{slug:string,text:string,level:int}> $toc_list Array of TOC items.
* @param int $post_id Post ID the TOC is being generated for.
* @return string Filtered TOC HTML.
*/
$toc_html = apply_filters( 'ttm_dynamic_toc_html', $toc_html, $toc_list, $post_id );
// Choose final output based on requested mode.
if ( 'toc' === $output ) {
$final = $toc_html;
} elseif ( 'content' === $output ) {
$final = $new_content;
} else {
$final = $toc_html . $new_content;
}
// Store in transient with hash for validation.
set_transient(
$cache_key,
array(
'hash' => $content_hash,
'html' => $final,
),
$cache_ttl
);
return $final;
}
/**
* Add the per-page TOC meta box to supported post types.
*
* The list of post types may be filtered via {@see 'ttm_dynamic_toc_meta_post_types'}.
*
* @since 1.1
* @return void
*/
function ttm_dynamic_toc_add_meta_box(): void {
$post_types = ttm_get_meta_post_types();
foreach ( (array) $post_types as $pt ) {
add_meta_box(
'ttm_dynamic_toc_meta',
__( 'Dynamic TOC', 'dynamic-toc' ),
__NAMESPACE__ . '\\ttm_dynamic_toc_meta_box_callback',
$pt,
'side',
'default'
);
}
}
add_action( 'add_meta_boxes', __NAMESPACE__ . '\\ttm_dynamic_toc_add_meta_box' );
/**
* Register post meta for the per-page TOC flag so it is available via REST/Gutenberg.
*
* Uses the same meta key filtered by `ttm_dynamic_toc_meta_key` and allows themes
* and plugins to show the flag in the REST API and block editor.
*
* @since 1.4.0
* @return void
*/
function ttm_dynamic_toc_register_post_meta(): void {
$meta_key = ttm_get_dynamic_toc_meta_key();
$post_types = ttm_get_meta_post_types();
// Register the post meta per post type to ensure compatibility with
// environments where passing an array to `register_post_meta` may cause
// unexpected runtime behavior. Iterate explicitly to avoid type issues.
$meta_args = array(
'type' => 'boolean',
'single' => true,
'show_in_rest' => true,
'sanitize_callback' => function ( $value ) {
return (bool) $value;
},
'auth_callback' => function () {
return current_user_can( 'edit_posts' );
},
);
foreach ( (array) $post_types as $pt ) {
register_post_meta( $pt, $meta_key, $meta_args );
}
}
add_action( 'init', __NAMESPACE__ . '\\ttm_dynamic_toc_register_post_meta' );
/**
* Meta box display callback.
*
* @since 1.1
* @param WP_Post $post Current post object.
* @return void Outputs the meta box HTML.
*/
function ttm_dynamic_toc_meta_box_callback( WP_Post $post ): void {
$meta_key = ttm_get_dynamic_toc_meta_key();
$value = get_post_meta( $post->ID, $meta_key, true );
wp_nonce_field( 'ttm_dynamic_toc_meta_box', 'ttm_dynamic_toc_meta_box_nonce' );
?>
<p>
<label for="ttm_dynamic_toc_enabled">
<input type="checkbox" name="ttm_dynamic_toc_enabled" id="ttm_dynamic_toc_enabled" value="1" <?php checked( $value, '1' ); ?> />
<?php esc_html_e( 'Show Table of Contents on this page', 'dynamic-toc' ); ?>
</label>
<br />
<span class="description"><?php esc_html_e( 'When checked, a collapsible Table of Contents will appear at the top of this page.', 'dynamic-toc' ); ?></span>
</p>
<?php
}
/**
* Save the per-page TOC meta and clear TOC transient.
*
* Performs nonce & capability checks, updates post meta, and deletes the per-post
* TOC transient so changes take effect immediately.
*
* @since 1.1
* @param int $post_id Post ID being saved.
* @return void
*/
function ttm_dynamic_toc_save_meta( int $post_id ): void {
// security checks.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( wp_is_post_revision( $post_id ) ) {
return;
}
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
$nonce = isset( $_POST['ttm_dynamic_toc_meta_box_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['ttm_dynamic_toc_meta_box_nonce'] ) ) : '';
if ( ! wp_verify_nonce( $nonce, 'ttm_dynamic_toc_meta_box' ) ) {
return;
}
$meta_key = ttm_get_dynamic_toc_meta_key();
$value = isset( $_POST['ttm_dynamic_toc_enabled'] ) ? '1' : '0';
update_post_meta( $post_id, $meta_key, $value );
// Clear cached TOC transient for this post so enabling/disabling or content changes take effect.
$keys = array( 'toc', 'content', 'both' );
$cache_key = 'ttm_toc_' . (int) $post_id;
foreach ( $keys as $k ) {
delete_transient( $cache_key . '_' . $k );
}
}
add_action( 'save_post', __NAMESPACE__ . '\\ttm_dynamic_toc_save_meta' );
/**
* Shortcode handler to render the TOC in-place.
*
* Usage: [dynamic_toc]
*
* When used as a shortcode, bypasses the per-post enable check since the user
* has explicitly inserted the block/shortcode. The filter ttm_dynamic_toc_enabled
* can still be used to prevent rendering if needed.
*
* @since 1.4.0
* @param array $atts Shortcode attributes (reserved for future use).
* @return string HTML markup for the TOC.
*/
function ttm_dynamic_toc_shortcode( $atts = array() ) {
global $post;
if ( empty( $post ) ) {
return '';
}
// When called via shortcode, the user explicitly wants the TOC,
// so we skip the per-post meta/option check and go straight to rendering.
// However, we still respect the global filter for override purposes.
$enabled = apply_filters( 'ttm_dynamic_toc_enabled', true, $post->ID );
if ( ! $enabled ) {
return '';
}
$content = get_post_field( 'post_content', $post->ID );
// When used as a shortcode, return only the TOC HTML so we don't
// inject the whole post content again (which caused duplication).
return automatic_toc( $content, (int) $post->ID, 'toc' );
}
add_shortcode( 'dynamic_toc', __NAMESPACE__ . '\ttm_dynamic_toc_shortcode' );
/**
* Render the TOC markup from a list of items.
*
* @since 1.1
* @param array<int,array{slug:string,text:string,level:int}> $toc_list Array of TOC items. Each
* item is an associative
* array with keys
* 'slug' => string,
* 'text' => string and
* 'level' => int.
* @return string TOC HTML markup.
*/
function toc( array $toc_list ): string {
ob_start();
/* Generate unique IDs so multiple TOCs on a page won't conflict. */
$uniq = wp_unique_id( 'ttm-toc-' );
$nav_label_id = 'ttm-toc-heading-' . $uniq;
$toggle_id = 'ttm-toc-toggle-' . $uniq;
$panel_id = 'ttm-toc-panel-' . $uniq;
$count = count( $toc_list );
?>
<nav class="ttm-toc" aria-labelledby="<?php echo esc_attr( $nav_label_id ); ?>">
<h2 id="<?php echo esc_attr( $nav_label_id ); ?>" class="screen-reader-text"><?php echo esc_html__( 'Table of contents', 'dynamic-toc' ); ?></h2>
<div class="ttm-toc__toggle">
<button id="<?php echo esc_attr( $toggle_id ); ?>" class="ttm-toc__button" type="button" aria-expanded="false" aria-controls="<?php echo esc_attr( $panel_id ); ?>">
<span class="ttm-toc__title"><?php echo esc_html__( 'Table of contents', 'dynamic-toc' ); ?></span>
<span class="ttm-toc__info">
<span class="ttm-toc__count">(<?php echo esc_html( (string) $count ); ?>)</span>
<span class="ttm-toc__icon" aria-hidden="true">+</span>
</span>
</button>
</div>
<div id="<?php echo esc_attr( $panel_id ); ?>" class="ttm-toc__panel" role="region" aria-labelledby="<?php echo esc_attr( $toggle_id ); ?>" hidden>
<?php
// Render a nested ordered list based on heading levels. Compute the minimum
// heading level present so we render lists starting from that base.
$levels = array_map(
static function ( $it ) {
return isset( $it['level'] ) ? (int) $it['level'] : 2;
},
$toc_list
);
$min_level = ! empty( $levels ) ? min( $levels ) : 2;
$prev_level = $min_level - 1;
foreach ( $toc_list as $item ) :
$level = isset( $item['level'] ) ? (int) $item['level'] : $min_level;
if ( $level < $min_level ) {
$level = $min_level;
}
if ( $level > $prev_level ) {
for ( $i = $prev_level + 1; $i <= $level; $i++ ) {
echo '<ol class="ttm-toc__list ttm-toc__list--level-' . esc_attr( $i ) . '">';
}
} elseif ( $level < $prev_level ) {
for ( $i = $prev_level; $i > $level; $i-- ) {
echo '</li></ol>';
}
echo '</li>';
} elseif ( $prev_level >= $min_level ) {
// Same level as previous, close previous li.
echo '</li>';
}
// Output current list item (left open so nested lists can be appended).
?>
<li class="ttm-toc__item"><a href="#<?php echo esc_attr( $item['slug'] ); ?>"><?php echo esc_html( $item['text'] ); ?></a>
<?php
$prev_level = $level;
endforeach;
// Close any remaining open lists.
for ( $i = $prev_level; $i >= $min_level; $i-- ) {
echo '</li></ol>';
}
?>
</div>
</nav>
<?php
return ob_get_clean();
}
/**
* Add the Dynamic TOC Tools admin page under Tools menu.
*
* @since 1.6.0
* @return void
*/
add_action(
'admin_menu',
function () {
add_submenu_page(
'tools.php',
__( 'Dynamic TOC Tools', 'dynamic-toc' ),
__( 'Dynamic TOC', 'dynamic-toc' ),
'manage_options',
'dynamic-toc-tools',
__NAMESPACE__ . '\\ttm_dynamic_toc_tools_page'
);
}
);
/**
* Render the Dynamic TOC Tools admin page.
*
* Provides a button to clear all TOC cache transients.
*
* @since 1.6.0
* @return void
*/
function ttm_dynamic_toc_tools_page(): void {
?>
<div class="wrap">
<h1><?php echo esc_html__( 'Dynamic TOC Tools', 'dynamic-toc' ); ?></h1>
<?php
// Handle form submission to clear cache.
if ( isset( $_POST['ttm_action'] ) && 'clear_cache' === sanitize_text_field( wp_unslash( $_POST['ttm_action'] ) ) ) {
$nonce = isset( $_POST['ttm_dynamic_toc_clear_cache_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['ttm_dynamic_toc_clear_cache_nonce'] ) ) : '';
if ( wp_verify_nonce( $nonce, 'ttm_dynamic_toc_clear_cache' ) ) {
$n = ttm_dynamic_toc_clear_all_cache();
echo '<div class="updated notice is-dismissible">
<p>' . esc_html( sprintf( __( '%d cached TOCs were removed.', 'dynamic-toc' ), $n / 2 ) ) . '</p>
</div>';
}
}
// Handle form submission to reset all data.
if ( isset( $_POST['ttm_action'] ) && 'reset_data' === sanitize_text_field( wp_unslash( $_POST['ttm_action'] ) ) ) {
$nonce = isset( $_POST['ttm_dynamic_toc_reset_data_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['ttm_dynamic_toc_reset_data_nonce'] ) ) : '';
if ( wp_verify_nonce( $nonce, 'ttm_dynamic_toc_reset_data' ) ) {
$n = ttm_reset_all_dynamic_toc_data();
echo '<div class="updated notice is-dismissible">
<p>' . esc_html__( 'All Dynamic TOC data has been reset.', 'dynamic-toc' ) . '</p>
<p>' . esc_html( sprintf( __( '%d post meta entries and cached TOCs were removed.', 'dynamic-toc' ), $n ) ) . '</p>
</div>';
}
}
?>
<p><?php echo esc_html__( 'Use the tools below to manage the Dynamic Table of Contents plugin.', 'dynamic-toc' ); ?></p>
<h2><?php echo esc_html__( 'Clear TOC Cache', 'dynamic-toc' ); ?></h2>
<p><?php echo esc_html__( 'Click the button below to clear all cached Table of Contents transients. This will force the TOCs to be regenerated on the next page load.', 'dynamic-toc' ); ?></p>
<form method="post" action="">
<?php wp_nonce_field( 'ttm_dynamic_toc_clear_cache', 'ttm_dynamic_toc_clear_cache_nonce' ); ?>
<input type="hidden" name="ttm_action" value="clear_cache" />
<?php submit_button( __( 'Clear TOC Cache', 'dynamic-toc' ), 'primary', 'submit', false ); ?>
</form>
<h2><?php echo esc_html__( 'Reset All Dynamic TOC Data', 'dynamic-toc' ); ?></h2>
<p><?php echo esc_html__( 'Click the button below to remove all Dynamic TOC data from your site, including per-post TOC settings and cached TOCs. This action cannot be undone.', 'dynamic-toc' ); ?></p>
<form method="post" action="" onsubmit="return confirm('<?php echo esc_js( __( 'Are you sure you want to reset all Dynamic TOC data? This action cannot be undone.', 'dynamic-toc' ) ); ?>');">
<?php wp_nonce_field( 'ttm_dynamic_toc_reset_data', 'ttm_dynamic_toc_reset_data_nonce' ); ?>
<input type="hidden" name="ttm_action" value="reset_data" />
<?php submit_button( __( 'Reset All Dynamic TOC Data', 'dynamic-toc' ), 'secondary', 'submit', false ); ?>
</form>
</div>
<?php
}
/**
* Clear all TOC cache transients.
*
* @since 1.6.0
* @return int Number of deleted transients.
*/
function ttm_dynamic_toc_clear_all_cache(): int {
if( current_user_can( 'manage_options' ) === false ) {
return 0;
}
global $wpdb;
$transient_name_like = '_transient_ttm_toc_%';
$transient_timeout_like = '_transient_timeout_ttm_toc_%';
$n = $wpdb->query(
$wpdb->prepare(
"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
$transient_name_like,
$transient_timeout_like
)
);
return (int) $n;
}
/**
* Clear all Dynamic TOC per-post meta entries.
*
* @since 1.6.0
* @return int Number of deleted post meta entries.
*/
function ttm_dynamic_toc_clear_post_meta_cache(): int {
if( current_user_can( 'manage_options' ) === false ) {
return 0;
}
global $wpdb;
// Delete all post meta entries related to Dynamic TOC.
$meta_key = ttm_get_dynamic_toc_meta_key();
$n = $wpdb->query(
$wpdb->prepare(
"DELETE FROM {$wpdb->postmeta} WHERE meta_key = %s",
$meta_key
)
);
return (int) ( $n / 2 );
}
/**
* Reset all Dynamic TOC data: per-post meta and cached TOCs.
*
* @since 1.6.0
* @return int Number of deleted post meta entries.
*/
function ttm_reset_all_dynamic_toc_data(): int {
// Clear all TOC cache transients.
$n = ttm_dynamic_toc_clear_all_cache();
// Clear all per-post TOC meta entries.
$m = ttm_dynamic_toc_clear_post_meta_cache();
return (int) $n + (int) $m;
}