I've been working with embeded content and as many already know, wordpress wraps the_content() lines in p tags.
So, found this:
$content = preg_replace('/<p>\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
return preg_replace('/<p>\s*(<iframe .*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content);
When I change "iframe" by "script" it works, but then only for one of them, I need both beacuse the twitter embbeds create a hidden script element wich in turn creates a ghost paragraph.
I've been working with embeded content and as many already know, wordpress wraps the_content() lines in p tags.
So, found this:
$content = preg_replace('/<p>\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
return preg_replace('/<p>\s*(<iframe .*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content);
When I change "iframe" by "script" it works, but then only for one of them, I need both beacuse the twitter embbeds create a hidden script element wich in turn creates a ghost paragraph.
Share Improve this question asked Sep 16, 2016 at 1:53 10Y0110Y01 591 silver badge10 bronze badges2 Answers
Reset to default 3This should do it and also remove <p>
tags from images that are linked.
Why it removes it from only one <script>
instance is hard to tell. Would have to see your website code to investigate further.
// Remove p tags from images, scripts, and iframes.
function remove_some_ptags( $content ) {
$content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
$content = preg_replace('/<p>\s*(<script.*>*.<\/script>)\s*<\/p>/iU', '\1', $content);
$content = preg_replace('/<p>\s*(<iframe.*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content);
return $content;
}
add_filter( 'the_content', 'remove_some_ptags' );
Here is a JavaScript function that does it:
moveIframesOutOfPtags() {
let iframes = document.querySelectorAll( 'iframe' );
let before = "<div class="iframe-container">";
let after = "</div>";
Object.entries( iframes ).forEach( entry => {
let value = entry[1];
if( value.parentNode.nodeName === 'P' || value.parentNode.nodeName === 'p' ){
value.parentNode.outerHTML = before + value.parentNode.innerHTML + after;
}
});
}
I've written a few more details over here.