Last active
January 3, 2023 01:11
-
-
Save ninnypants/1668216 to your computer and use it in GitHub Desktop.
Remove empty p tags from WordPress posts
This file contains 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 | |
add_filter( 'the_content', 'remove_empty_p', 20, 1 ); | |
function remove_empty_p( $content ){ | |
// clean up p tags around block elements | |
$content = preg_replace( array( | |
'#<p>\s*<(div|aside|section|article|header|footer)#', | |
'#</(div|aside|section|article|header|footer)>\s*</p>#', | |
'#</(div|aside|section|article|header|footer)>\s*<br ?/?>#', | |
'#<(div|aside|section|article|header|footer)(.*?)>\s*</p>#', | |
'#<p>\s*</(div|aside|section|article|header|footer)#', | |
), array( | |
'<$1', | |
'</$1>', | |
'</$1>', | |
'<$1$2>', | |
'</$1', | |
), $content ); | |
return preg_replace('#<p>(\s| )*+(<br\s*/*>)*(\s| )*</p>#i', '', $content); | |
} |
Wanted to chime in to say 'thank you' for this gist. I was finally fed up with a crappy theme I'm using that aggressively added empty tags every time you hit save on a page. (Going to be moving away from the theme in the future, but gotta get through the next 2 months first). This is/was a life saver.
Adding this jQuery works perfectly fine for me
$('p').each(function() { const $this = $(this); if($this.html().replace(/\s| /g, '').length === 0) $this. Remove(); });
If the p tag is completely empty without space or  , then this should work
$( 'p:empty' ).remove();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not working for me.. I have a shortcode that outputs a link along with a div container that is hidden with CSS and called when the link is clicked (as a modal). The div container, being a block element, causes the shortcode to end the paragraph early, show the div and then just has the remaining text sort of floating there unwrapped by anything.
So... let's say I have something like this in the tinymce:
Blah blah blah [popup id=5 text="click me to open the popup this should be inline with this blah blah paragraph"] and then the sentence continues.
The HTML output ends up being:
Was hoping your function would get me output that looked like:
<p>Blah blah blah <div id="popup-5" class="popup-modal">click me to open... paragraph</div> and then the sentence continues.</p>
Any ideas? Thank you!