8

I'm wanting to remove the p tags that wrap img tags by default in ckeditor.

I don't want to totally disable p tags or change the EnterMode to another tag. I only want to stop images being wrapping in paragraphs.

I want this done client side, not server side.

I have:

<p>Some text in a parapgraph.</p>

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

<p>Another paragraph</p>

I want:

<p>Some text in a parapgraph.</p>

<img src="picture.jpg">

<p>Another paragraph</p>
Ric
  • 3,195
  • 1
  • 33
  • 51
  • 5
    Downvoters - at least say why you're downvoting. Seems like a perfectly reasonable question to me. If you explained why it isn't then maybe not only the asker but others reading might learn something. Upvoted to counter. – Nick Rice Nov 20 '14 at 14:25

2 Answers2

0

Quick fix:

This will work if there is nothing else on the line except the three tags.

$str = "<p><img src=\"/file.jpg\" width=\"1\" height=\"2\" /></p>"
$replaced = preg_replace ( "/<p[^>]*?>(<img[^>]+>)<\/p>/" , "$1" , $str )

Updated:

Here is a PHP function. You can call it from JavaScript.

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');

Reference

ummahusla
  • 2,043
  • 3
  • 28
  • 42
0

jQuery solution to unwrap the img tag at display time. (It won't stop the paras being put in though.)

<script>
    $("p img").unwrap();
</script>

It will also unwrap any other images you have on the page, so you'd probably want a tighter selector.

Nick Rice
  • 1,163
  • 1
  • 13
  • 21