Created
November 4, 2016 00:28
-
-
Save vinicio/da4c752e62bf9b561e9b34e01ad710cc to your computer and use it in GitHub Desktop.
Remove paragraph tags around images in WordPress post/page content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Move image inside <p> tag above the <p> tag while preserving any link around image. | |
* Can be prevented by adding any attribute or whitespace to <p> tag, e.g. <p class="yolo"> or even <p > | |
*/ | |
function remove_p_around_img($content) | |
{ | |
$contentWithFixedPTags = preg_replace_callback('/<p>((?:.(?!p>))*?)(<a[^>]*>)?\s*(<img[^>]+>)(<\/a>)?(.*?)<\/p>/is', function($matches) { | |
$image = $matches[2] . $matches[3] . $matches[4]; | |
$content = trim( $matches[1] . $matches[5] ); | |
if ($content) { | |
$content = '<p>'. $content .'</p>'; | |
} | |
return $image . $content; | |
}, $content); | |
// On large strings, this regular expression fails to execute, returning NULL | |
return is_null($contentWithFixedPTags) ? $content : $contentWithFixedPTags; | |
} | |
add_filter('the_content', 'remove_p_around_img'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment