public
Last active

WordPress Image P tag remover plugin

  • Download Gist
image_ptag_remover.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
<?php
/*
Plugin Name: Image P tag remover
Description: Plugin to remove p tags from around images and iframes in content outputting, after WP autop filter has added them. (oh the irony)
Version: 1.1
Author: Fublo Ltd
Author URI: http://blog.fublo.net/2011/05/wordpress-p-tag-removal/
*/
 
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...
$content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
// now pass that through and do the same for iframes...
return preg_replace('/<p>\s*(<iframe .*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content);
}
 
// we want it to be run after the autop stuff... 10 is default.
add_filter('the_content', 'filter_ptags_on_images');

This code was originally posted on WordPress Stack Exchange, in response to a question which we were also working on - http://wordpress.stackexchange.com/questions/7090/stop-wordpress-wrapping-images-in-a-p-tag

Now updated to rip iframes too. If you want the original code that just ripped the p tags off images, then you can roll back this gist's history to here : https://gist.github.com/975026/230855aa732a602045b2531fd7586ecb49a57359

James, I know this code is quite old, but does this code work in wp editor? It works for me on page, but doesn't work in editor. Image still wrapped.
Thanks

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.