最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

the content - removing <p> tags around img, iframes and also scripts

programmeradmin2浏览0评论

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 badges
Add a comment  | 

2 Answers 2

Reset to default 3

This 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.

发布评论

评论列表(0)

  1. 暂无评论