I have 2 WordPress shortcodes I am working on:
- A Chapter. [chapter name="the begining"]...content...[/chapter]
- A table of contents [toc][/toc]. The toc needs to display a simple list of the chapters.
Specification:
- There can be many chapters in a post.
- There can be one, two or no toc shortcode in a post.
- The toc can be either before or after the chapters or both before and after. It is up to the post writer so I don't know in advance.
- I cannot use nested shortcodes as those are difficult for writers to work with.
I thought of using a static toc array to add chapters at each chapter tag and then output it in the toc shortcode. Alas, the toc shortcode can appear BEFORE the chapters and then the array will be empty.
The following post html will not show the toc:
[toc][/toc]
Here is some content
[chapter name="hello"]xxx[/chapter]
In between content may come here
[chapter name="world"]yyy[/chapter]
Some more stuff
This is my starting code (embeded in a class):
public static function register_chapter_shortcode($atts, $content=null){
$atts = shortcode_atts (
array (
'name' => '',
), $atts );
$name = $atts["name"];
if (self::$toc == null){
self::$toc = array ($name);
} else {
array_push(self::$toc, $name);
}
return '
<h2>'.$atts["name"].'</h2>
<div>'.do_shortcode($content).'</div>'
;
}
public static function register_toc_shortcode($atts, $content=null){
$items = "";
foreach (self::$toc as $item){
$items = $items. '<li><a href="#">'.$item.'</a></li>';
}
return '
<ul>'.$items.'</ul>
';
}