X

Automatically Wrap Images in the_content with Custom HTML

Snippets by IsItWP

Do you want to automatically wrap images in the_content with custom HTML? Images always break content into paragraphs. However, you can easily wrap them with your content using the custom HTML.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:


function filter_images($content){
    return preg_replace('/<img (.*) \/>\s*/iU', '<span class="className"><b><img \1 /></b></span>', $content);
}
add_filter('the_content', 'filter_images');

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 27 best WordPress business themes for your website and 15 best content marketing tools and plugins for WordPress.

Comments   Leave a Reply

  1. 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. Help plz!

  2. great!

  3. I love you man! great script

Add a Comment Cancel reply

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!