Skip to content

Instantly share code, notes, and snippets.

Last active January 3, 2023 01:11
  • Star 64 You must be signed in to star a gist
  • Fork 22 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Remove empty p tags from WordPress posts
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(
'#</(div|aside|section|article|header|footer)>\s*<br ?/?>#',
), array(
), $content );
return preg_replace('#<p>(\s|&nbsp;)*+(<br\s*/*>)*(\s|&nbsp;)*</p>#i', '', $content);
Copy link

EliW commented Sep 10, 2019

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.

Copy link

justiceakorede commented Nov 18, 2022

Adding this jQuery works perfectly fine for me

$('p').each(function() { const $this = $(this); if($this.html().replace(/\s|&nbsp;/g, '').length === 0) $this. Remove(); });

If the p tag is completely empty without space or &nbsp, 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