0

I am trying to generate a Table of Contents at the top of each of my posts and would like to minimize the requirements on the author. Ideally, the author would enter only various levels of the header tag along with an anchor link -- e.g. <h1 id="introduction>Introduction</h1> -- and the WP function would scoop all the header tags' text content and links to generate the table.

While this would be relatively straightforward to do in the browser with JS, that feels hack-y to me and would hurt SEO. Is there a good way to do this server-side?

1 Answer 1

3

Sure. In your single.php or where you loop through the posts, start by getting the content:

$content = get_the_content();

Then use a regex where you target anything within <h2> tags:

$regex = '/<h2>(.*?)\<\/h2>/u';

And then use preg_match_all() to find all titles:

preg_match_all($regex, $content, $table_of_content);

This will create a multidimensional array, see:

print_r($table_of_content);

So you have the titles stored in $table_of_content[0].

Using this array, and a variation of the regex to get the id or data-attribute which I would go with, you're set to go.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.