Remove Empty Paragraphs from WordPress Post Content with the_content Filter

Remove empty paragraphs from the_content()

Empty paragraphs spoil not only the look of a site, with random gaps between blocks, but also the markup that search engines see. They come from the classic editor, from shortcodes surrounded by line breaks, and from content pasted from Word. That is why this fix is useful for almost every theme.

Problem: How to remove empty paragraphs (<p></p>, <p>&nbsp;</p>) from the output of the_content()?

Solution: All such tasks are solved with filters. Add to functions.php:

<?php
// Remove empty paragraphs from the_content()
add_filter( 'the_content', 'remove_empty_paragraphs', 20 );

function remove_empty_paragraphs( $content ) {
    $content = force_balance_tags( $content );
    return preg_replace( '#<p>(?:\s|&nbsp;|\x{00A0})*</p>#iu', '', $content );
}

The regular expression removes paragraphs that contain only spaces, line breaks, &nbsp; entities or the non-breaking space character itself (the u modifier is needed for it). force_balance_tags() closes unclosed tags first, so the replacement does not break the markup.

The priority 20 runs the filter after wpautop (priority 10), which adds the paragraphs, and after shortcodes are processed (priority 11).

The same function works for ACF WYSIWYG fields and text widgets:

<?php
add_filter( 'acf/format_value/type=wysiwyg', 'remove_empty_paragraphs', 20 );
add_filter( 'widget_text_content', 'remove_empty_paragraphs', 20 );

NOTE: Sometimes an empty paragraph is used on purpose as a spacer. After this filter it disappears, so use margins in CSS or the Spacer block instead.