0

How can I achieve something where I can use a PHP foreach loop which will loop through`the_content() of a WordPress post/page, find H2 tags and wrap each H2 section in a div?

I want to alternate between:

<div class="content animate-on-view fadeInUp wrap">

and

<div class="content even animate-on-view fadeInUp wrap">

But I'm not sure how to achieve this. How would I get the post content and find the H2 tags and then wrap the H2 sections (all the content up until the next H2 tag or the end of the post) in the above divs?

Thanks :)

Shiv
  • 831
  • 1
  • 12
  • 29

1 Answers1

0

Here is a working prototype, but I strongly advise against using such methods for performance reasons.

<?php
ob_start();
?>
<h2>Lorem Ipsum is simply dummy text of the printing</h2> and typesetting industry. <h2>Lorem Ipsum has been the industry's</h2> standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
<?php
$text = ob_get_contents();
$tagname = "h2";
$regex = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match_all($regex, $text, $matches);
for($i=0;$i<count($matches[0]);$i++)
{
    if ($i % 2 == 0)
    {
        $text = str_replace($matches[0][$i], '<div class="content animate-on-view fadeInUp wrap">'.$matches[0][$i].'</div>', $text);
    }
    else
    {
        $text = str_replace($matches[0][$i], '<div class="content even animate-on-view fadeInUp wrap">'.$matches[0][$i].'</div>', $text);
    }
}

You should brake this into smaller problems and would have been able to do it yourself:

  1. How to match content between html tags with REGEX
  2. Iterate through the result and use the odd/even test to change between the tags you want...
Community
  • 1
  • 1
Pavel Petrov
  • 730
  • 9
  • 11