Howto: Stop WordPress Wrapping Images In A “P” Paragraph Tag : Images are a crucial piece to the overall look and feel of pretty much every WordPress blog or website. When images are uploaded to the post content, the default of WordPress is to wrap them in paragraph tags. This however adds extra unwanted markup and can also affect and cause problems with the inner styling of your content blocks. In this tutorial we will teach you how to remove the unwanted paragraph tag from images uploaded to the post content by using a simple WordPress function.

WordPress has the unfortunate tendency of wrapping nearly everything in <p> tags. While this is often helpful for blocks of text in a post, it limits our ability to succinctly and consistently style images regardless of their containing <a> tag, <p> tag, or both. In other words, you rarely want <a> tag styles (e.g. border-bottom & :hover) or <p> styles (e.g. margin-bottom & max-width) to affect the styling of their child images.

Howto: Stop WordPress Wrapping Images In A “P” Paragraph Tag

In case you want to have  in your content but not have them get “Auto P’d” like WordPress likes to do.

example of problem:

blah blah blah
<img src="monkey.jpg">
blah blah blah

 

is turned into

 

<p>blah blah blah</p>
<p><img src="monkey.jpg"></p>
<p>blah blah blah</p>

 

BUT BUT BUT…. here’s what I did yesterday on a client site that I was having this exact problem with… I mixed and matched a few quick lines of code into your functions.php file and save it.

and BAAMMMM!!! Have a try and let me know if it works or not!

 

function filter_ptags_on_images($content)
{
    // do a regular expression replace...
    // find all p tags that have just
    // <p>maybe some white space<img all stuff up to /> then maybe whitespace </p>
    // replace it with just the image tag...
    return preg_replace('/<p>(\s*)(<img .* \/>)(\s*)<\/p>/iU', '\2', $content);
}

// we want it to be run after the autop stuff... 10 is default.
add_filter('the_content', 'filter_ptags_on_images');