Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress' wpautop adds line breaks and empty paragraphs in some cases, especially when the first item in the post is an image. This attempts to strip those tags which may be desirable if you have special paragraph styling or have a consistently desired post format.
<?php
function remove_empty_p($content)
{
$content = force_balance_tags($content);
$return = preg_replace('#<p>\s*+(<br\s*/*>)?\s*</p>#i', '', $content);
$return = preg_replace('~\s?<p>(\s|&nbsp;)+</p>\s?~', '', $return);
return $return;
}
add_filter('the_content', 'remove_empty_p', 20, 1);
?>
@davidrichied
Copy link

davidrichied commented Dec 18, 2016

Warning*
This code breaks the Ninja Forms plugin, somehow. It only breaks it when adding a little bit of complexity to the form. I found out by process of elimination. It must remove some JavaScript somewhere. The JS errors I get are below.

SyntaxError: expected expression, got '<'[Learn More] website-request-form:282:8
ReferenceError: nfForms is not defined[Learn More] front-end.js:1:8202

@quinnkeast
Copy link

quinnkeast commented Feb 7, 2017

After a lot of tedious troubleshooting, I've discovered that this also breaks Gravity Forms ajax submissions.

Gravity Forms injects inline jQuery, which should look similar to:

jQuery('#gform_wrapper_1').replaceWith('<' + 'div id=\'gforms_confirmation_message

However, with this gist, it adds a phantom space:

jQuery('#gform_wrapper_1').replaceWith('< ' + 'div id=\'gforms_confirmation_message

It's being caused specifically by this line:

$content = force_balance_tags( $content );

I don't have a solution to offer, but perhaps someone else with this issue will save a few hours of troubleshooting.

@dskvr
Copy link

dskvr commented Jun 22, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment