0

How would I grab specific tags from the_content? For example, I'd like to pull a list of all h1 tags.

1 Answer 1

3

Using preg_match_all() you can create a regex pattern to find and extract tags (and their content).

With Wordpress's post_content hook, you can find and list all the H1's within current posts content with something like:

add_action('the_content', function ($content){

    // look for <h1> tags and text therein, anticipate class/id name
    $findH1s = preg_match_all('/<h1 ?.*>(.*)<\/h1>/i', $content, $h1s);

    // if found, show above content
    if (is_array($h1s) && isset($h1s[0]))   
        return "<pre>H1's in this post: ".print_r( $h1s[0] ,true)."</pre>".$content;

    // if none found, just return content as-is
    return $content;
});
2
  • Worked like a charm. I need to spend more time figuring out how to write regex patterns, as it has always been a deficiency of mine. Thanks so much, David. Dec 21, 2017 at 22:07
  • no problem. learning regex is worth every minute put into it. tools like www.phpliveregex.com and regex101.com are great when learning as well. Dec 21, 2017 at 22:15

Your Answer

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

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