Filter out empty lines in WordPress

I’m trying to add two captioned images in the WordPress editor and the Visual Editor keeps adding an empty paragraph between them. I don’t want an empty paragraph there — I got a nice CSS setup going on in the front end and that empty line is messing it up.

Extra Paragraph

The only way I could find to take care of this (other than reinventing the Visual Editor) was to add a filter to the WordPress content and have any occurrence of <p>&nbsp;</p> removed from the HTML.

This code goes in functions.php (which is in your theme folder):

// Strip out all <p>&nbsp;</p> from the content
function strip_empty_lines($content) {
    $content = str_replace('<p>&nbsp;</p>','',$content);
    return $content;
}
add_filter ('the_content', 'strip_empty_lines');

For your reference:

Posted in blog Tagged with: , ,
2 comments on “Filter out empty lines in WordPress
  1. Martin says:

    Hi.. I replaced the $content for $excerpt, and removed the paragraph tags, but my excerpt still has unwanted spaces in it.

    Any help would be much appreciated.

    • Stefan says:

      It’s probably because that filter (last line in the code) is still hooked to ‘the_content’.

      Try replacing it with this: add_filter ('get_the_excerpt', 'strip_empty_lines');