setting_enabled['toggle-advanced']) || empty($siteseo->advanced_settings['toc_enable'])){ return; } add_filter('the_content', '\SiteSEO\TableofContent::add_ids_to_headings'); } static function render_toc(){ global $siteseo; if(empty($siteseo->setting_enabled['toggle-advanced']) || empty($siteseo->advanced_settings['toc_enable'])){ return; } static $siteseo_toc_run = false; if(!empty($siteseo_toc_run)){ return '
'.esc_html__('Table of content shortcode can be used only once on a page, this page is using the shortcode more than once. Please remove the extra table of content shortcodes for this warning to go away.', 'siteseo').'
'; } $options = get_option('siteseo_advanced_option_name'); //$options = $siteseo->advanced_settings; $content = get_the_content(); if(empty($content)){ return; } $heading_type = (!empty($options['toc_heading_type']) ? $options['toc_heading_type'] : 'ul'); $dom = new DOMDocument(); $internalErrors = libxml_use_internal_errors(true); $dom->preserveWhiteSpace = false; $html = ''; if($dom->loadHTML('' . $content)){ $xpath = new DOMXPath($dom); $heading_list = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']; $headings_to_scan = []; foreach($heading_list as $h){ if(!empty($options['toc_excluded_headings']) && is_array($options['toc_excluded_headings']) && in_array($h, $options['toc_excluded_headings'])){ continue; } $headings_to_scan[] = '//'.$h; } if(empty($headings_to_scan)){ return; } $headings_to_scan = implode('|', $headings_to_scan); // The imploded string will look like this //h1|//h2|//h3|//h4|//h5|//h6 $headings = $xpath->query($headings_to_scan); if(empty($headings)){ return; } $last_h = 0; $open_ul = 0; $html .= ''.(!empty($options['toc_label']) ? esc_html($options['toc_label']) : esc_html__('Table of Content', 'siteseo')).'
<'.esc_html($heading_type).'>'; foreach($headings as $heading){ $title = trim(wp_strip_all_tags($heading->nodeValue)); $id = $heading->getAttribute('id'); $current_h = (int) substr($heading->tagName, 1); if(empty($id)){ $id = '#'.self::title_to_id($title); }else{ $id = '#'.$id; } if($current_h > $last_h){ $html .= '<'.esc_html($heading_type).'>'; $open_ul++; }else{ while($current_h <= $open_ul){ $html .= ''.esc_html($heading_type).'>'; $open_ul--; } } $html .= '