Remove paragraphs wrapping images in WYSIWYG

Posted in Snippets

When you press Add Media and add an image through the Media library in the WYSIWYG editor, an paragraph is wrapped around the inserted image. Usually you have margins around the paragraph which may cause the image to screw with the layout.

Hopefully, this will all change with the new Gutenberg editor

The snippet below will remove that paragraph and just leave the image in place.

/* 
 * Remove paragraph around images in the_content
 */
add_filter('the_content', function ($content) {
    return preg_replace('/<p>\s(<a .>)?\s(<img . \/>)\s(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
});