Table of contents
Previous article Next articleGenerate a table of contents for your pages based on the heading tags. It requires, depending on how you want to use it, IDs or anchors in your page.
This article originates from the former CMSMS Wiki, the original authors are Elijah Lofgren and Simon Schaufelberger.
User Defined Tag, named "table_of_contents"
* Generates a table of contents based on parameters you want
* @example: <h2 id="packages">Packages</h2> use: tag="h2" type="id"
* @example: <a name="packages">Packages</a> use: tag="a" type="name"
*/
function get_table_of_contents($page_contents, $tag, $type)
{
preg_match_all("/<$tag $type=\"([a-z-0-9]+)\">(.*)<\/$tag>/i", $page_contents, $match);
if (false == empty($match[0]))
{
$contents = "<ul>\n";
foreach ($match[1] as $key => $value)
{
if ($type == $match[1][$key])
{
$contents .= '';
}
else
{
$contents .= ' ';
}
$contents .= '<li><a href="'.$_SERVER['REQUEST_URI'].'#'.$match[1][$key].'">'.$match[2][$key].'</a>';
// Start a new sub-list if this item has children otherwise just end the list item
if (false == empty($match[1][$key + 1]) && $match[1][$key + 1] == $match[1][$key] + 1)
{
$contents .= "\n <ul>\n";
$unclosed_list = TRUE;
}
else
{
$contents .= "</li>\n";
}
// If the next item is higher level then close this list item
// In example current item is h3 and next is h2
if (false == empty($match[1][$key + 1]) && $match[1][$key + 1] == $match[1][$key] - 1)
{
$contents .= " </ul>\n</li>\n";
$unclosed_list = FALSE;
}
}
if (false == empty($unclosed_list))
{
$contents .= " </ul>\n</li>\n";
}
$contents .= "</ul>\n";
}
else
{
$contents = '';
}
return $contents;
}
echo get_table_of_contents($params['thepagecontent'], $params['tag'], $params['type']);
How to use
For use with IDs put in your template:
{table_of_contents thepagecontent=$pagecontent tag='h2' type='id'}
{$pagecontent}
For use with Anchors put in your template:
{table_of_contents thepagecontent=$pagecontent tag='a' type='name'}
{$pagecontent}
Comment Form
ReviewManager
ReviewManager
2 Comments
I see that your cmscanbesimple.org website could be missing out on approximately 1,000 visitors daily. Our AI powered traffic system is tailored to enhance your site's visibility: https://ln.run/_s3yp
We're offering a free trial that includes 4,000 targeted visitors to show the potential benefits. After the trial, we can supply up to 250,000 targeted visitors per month. This solution could greatly enhance your website's reach and engagement.
Replace in your template:
{content}
with:
{content assign='pagecontent'}
{table_of_contents thepagecontent=$pagecontent tag='h2' type='id'}
{$pagecontent}
Very nice - exactly what I am looking for. The only difficulty is: how to get it into the template? I use the standard "Left simple navigation + 1 column" and it complains about "duplicate content_en block". Any idea about this?