Skip to content

Instantly share code, notes, and snippets.

@tammalee
Last active April 2, 2023 18:49
Show Gist options
  • Save tammalee/e9ab6c9d040fcbd322a585f6f5c971f7 to your computer and use it in GitHub Desktop.
Save tammalee/e9ab6c9d040fcbd322a585f6f5c971f7 to your computer and use it in GitHub Desktop.
Remove P tags wrapping around images and iframes
<?php
/**
* Removes P tags from around images and iframes
* Original source: https://interconnectit.com/blog/2011/06/16/how-to-remove-p-tags-from-images-in-wordpress/
* @param [type] $pee [description]
* @return [type] [description]
*/
function img_unautop($pee) {
// commented out example shows how you can wrap your IMG tag in a div if you like
/* $pee = preg_replace('/<p>\\s*?(<a .*?><img.*?><\\/a>|<img.*?>)?\\s*<\\/p>/s', '<div class="figure">$1</div>', $pee); */
//strip P tag and just return the image
$pee = preg_replace('/<p>\\s*?(<a .*?><img.*?><\\/a>|<img.*?>)?\\s*<\\/p>/s', '$1', $pee);
//strip P tag and just return the iFrame
$pee = preg_replace('/<p>\s*(<iframe .*>*.<\/iframe>)\s*<\/p>/iU', '\1', $pee);
return $pee;
}
add_filter( 'acf_the_content', 'img_unautop', 30 ); //only use this one if you have ACF content
add_filter( 'the_content', 'img_unautop', 30 ); //regular content for POSTS and PAGES
@tammalee
Copy link
Author

tammalee commented Apr 8, 2017

WordPress has a nasty habit of adding P tags around images when you insert them into the content. This won't fix things like if you need to align an image etc. but it will strip the P tag out so you can target images for spacing etc. I also expanded the functionality to remove P tags from around iframes.

@IntrepidRealist
Copy link

Thank you! This works wonderfully!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment