I have this code that creates a dynamic TOC inside single.php at the top of the page. But I would like to use it in a shortcode.
I tried using add_shortcode('toc_content', 'create_toc');
but it does not display anything. Any idea what am I doing wrong?
function create_toc($html) {
$toc = '';
if (is_single()) {
if (!$html) return $html;
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
libxml_clear_errors();
$toc = '<div class="toc-bound">
<div class="toc-ctr">
table of contents
</div>
<ul class="toc">';
$h2_status = 0;
$i = 1;
$xpath = new DOMXpath($dom);
$expression = '//*[contains(concat(" ", normalize-space(@class), " "), " toc-item ")]';
foreach ($xpath->evaluate($expression) as $element) {
if($h2_status){
$toc .= '</li>';
$h2_status = 0;
}
$h2_status = 1;
$toc .= '<li><a href="' . get_the_permalink() . '#toc-' . $i . '">' . $element->textContent . '</a>';
$element->setAttribute('id', 'toc-' . $i);
$i++;
}
if($h2_status){
$toc .= '</li>';
}
$toc .= '</ul></div>';
$html = $dom->saveHTML();
}
return $toc . $html;
}
add_filter('the_content', 'create_toc');
//add_shortcode('toc_content', 'create_toc'); does not work