Stop WordPress Wrapping Images In A “P” Tag

I have searched high and low for a simple solution to this, but to no avail. WordPress keeps on wrapping my images in p tags and because of the eccentric nature of the layout for a site I am working on, this is highly annoying.

I have created a jQuery solution to unwrap images, but it isn’t that great. It lags because of other stuff loading on the page and so the changes are slow to be made. Is there a way to prevent WordPress wrapping just images with p tags? A hook or filter perhaps that can be run.

This is happening when uploading an image and then inserting it into the WYSIWYG editor. Manually going into the code view and removing the p tags is not an option as the client is not that technically inept.

I understand that images are inline, but the way I have the site coded images are inside of divs and set to block, so they are valid code.

1
11

here’s what we did yesterday on a client site that we were having this exact problem with… I created a quick filter as a plugin and activated it.

<?php
/*
Plugin Name: Image P tag remover
Description: Plugin to remove p tags from around images in content outputting, after WP autop filter has added them. (oh the irony)
Version: 1.0
Author: Fublo Ltd
Author URI: http://fublo.net/
*/

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

If you drop that into a php file in your /wp-content/plugins folder and then activate it, it should remove the p tags from any para that just contains an image.

I’m not sure how strong the regexp is in terms of if it will fail with outputs from other editors – for example if the img tag is closed with just > it will fail. If anyone has anything stronger, that would be really helpful.

Cheers,

James

— Improved filter —

To work with images that are wrapped in links, it keeps the links in the output and removes the p tags.

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

Leave a Comment