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.