Skip to content

Instantly share code, notes, and snippets.

@hagronnestad
Last active September 27, 2021 19:09
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hagronnestad/5336369 to your computer and use it in GitHub Desktop.
Save hagronnestad/5336369 to your computer and use it in GitHub Desktop.
WordPress: Wrap images in DIV.
// =======================
// = WRAP IMAGES IN DIVS =
// =======================
function wrapImagesInDiv($content) {
$pattern = '/(<img[^>]*class=\"([^>]*?)\"[^>]*>)/i';
$replacement = '<div class="image-container $2">$1</div>';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
add_filter('the_content', 'wrapImagesInDiv');
@andri
Copy link

andri commented Sep 23, 2015

Slight issue, if you use a caption, the caption text ends up outside of the div. I would also use the figure element, thats what WP uses if an image has a caption.

@RichardLindhout
Copy link

@andri +1

@igorescobar
Copy link

What about the images outside of the post? Like images on the layout?

@FrankPrendergast
Copy link

Thank you for this. Is there any possibility you would consider updating this to work with Gutenberg?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment