Automatically wrap multiple images in div

There are a few questions that are similar to this but I have not found anything that works with the latest version of WordPress.
I am trying to wrap adjacent images into the one div.

<p>
<img> />
<img> />
<img> />
Some text.
</p>

into:

<p>
<div>
<img> />
<img> />
<img> />
</div>
Some text.
</p>

I can wrap each image into its own div using:

function wrapImagesInDiv($content) {
$pattern = ‘/(<img[^>]*class=”([^>]*?)”[^>]*>)/i’;
$replacement = ‘<div>$1</div>’;
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
add_filter(‘the_content’, ‘wrapImagesInDiv’);

and I think it would be possible to edit the regex to wrap multiple img tags using {2,} but have failed to get it to work.

Any ideas?

Read more here:: Automatically wrap multiple images in div

Leave a Reply

Your email address will not be published. Required fields are marked *