How do I get the fully formatted content of a page in Wordpress?

97 Views Asked by At

I'm relatively new to Wordpress, so I hope this isn't a dumb question. I have the code below, the first part -- anchor_content_h2($content) -- that added the id to my h2 in content, works great.

    function anchor_content_h2($content) {

$pattern = '/<h2 class="hu2(.*?)>(.*?)<\/h2>/';

$content = preg_replace_callback($pattern, function ($matches) {
            $begin = $matches[1];
            $title = $matches[2];
            $slug = sanitize_title_with_dashes($title);
            return '<h2 ' . $begin . 'id="' . $slug . '">' . $title . '</h2>';
        }, $content);
return $content;
}

add_filter('the_content', 'anchor_content_h2');


function toc(){
global $post;
$content = $post->post_content;
$renderedcontent = apply_filters('the_content', $content);

preg_match_all(
            '/<h2.*?id="(.*?)".*?>(.*?)<\/h2>/',
            $renderedcontent,
            $matches
        ) ;
        $matches = array_combine($matches[1], $matches[2]);
        if (!empty($matches)){
           echo '<div class="sixteen wide column" style="padding-top: 3px;"><div class="ui horizontal divided list scroll-to">';
            foreach($matches as $id => $title):
                echo '<a class="ui item horizontal-toc" style="font-size: 1.2rem; font-weight:800; padding-left: 7px; padding-right: 7px; border-right: 2px solid rgba(34,36,38,.25); line-height:0.75em!important;" data-value="' . $id . '" href="#' . $id . '">' . $title . '</a>';
                endforeach;
    echo '</div></div>'; 

        }
}
add_shortcode('customtoc', 'toc')

When I get to function toc(), i run into some issue. everything after preg_match_all()... works great (i tested it with $renderedcontent as just a regular string with h2s in it and it gave me exactly what i expected). The only problem is getting the $renderedcontent to actually be the fully formatted content - I need my h2 filter I added to run so the ids are put in and I also need to access the content of the shortcodes as some have h2s in there as well (the ids are hardcoded in those).

I have tried so many different variations and ways (based on what I found online and just me trying stuff) but nothing seems to work. The one that seemed to come up the most was the apply_filter, but it hasn't worked so far. I don't get any errors when using the shortcode [customtoc] on page, it just shows nothing. I figure it's because the $renderedcontent doesn't actually contain any matches to the regex pattern in the function. Any help would be appreciated.

0

There are 0 best solutions below