Remove wrapping p from img in ckeditor

1.3k Views Asked by At

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>
2

There are 2 best solutions below

1
On

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

0
On

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.