Remove Paragraph Tags From Around Images

0
0

In case you want to have <img> 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

turns into:

<p>blah blah blah</p>

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

<p>blah blah blah</p>

We can fix it with this:

function filter_ptags_on_images($content){
   return preg_replace('​/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}

add_filter('the_content', 'filter_ptags_on_images');

Be very careful if you copy and paste the above. I had to put a zero-width space after the opening ‘ in the preg_replace function to solve a rendering issue. When copy and pasting, you’ll definitely need to remove zero-width space.

For your `functions.php` file, or, see Reference URL for a plugin. With this in place, we get:

<p>blah blah blah</p>

<img src="monkey.jpg">

<p>blah blah blah</p>

… meaning things like floating the images will be much easier.

  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.