WordPress Shortcode Whitespace (Empty Paragraph Tags)


I know shortcodes are going out, but for anyone stuck in the past, here's a hack to help clear up empty paragraph tags from your shortcodes in WordPress.

There's an older site I am helping maintain that uses shortcodes. The last time I was helping clean up a few things, I noticed the shortcodes were producing empty paragraph tags around the content of the shortcode. One way to take care of this is with a short bit of CSS (assuming you don't have any other place this would cause a problem).

p:empty {
  display: none;

One problem for me was they were putting HTML comments in the page content <!-- something --> and that little trick wasn't working. This is really hacky, but the quickest solution was to run the content through a "cleaning" method before returning the shortcode.

function some_shortcode($atts, $content = null) {
    $content = clean_shortcode_text($content); // <-- adding this to the shortcode functions
    return do_shortcode($content);
add_shortcode('the_shortcode', 'some_shortcode');

function clean_shortcode_text($text = '') {
    // Replace all empty paragraph tags that WordPress adds
    $tags = array("<p>", "</p>");
    $text = str_replace($tags, "\n", $text);

    // Remove any extra line breaks tags
    $tags = array("<br>", "<br/>", "<br />");
    $text = str_replace($tags, "", $text);

    // Remove HTML comments that will create empty paragraphs with the HTML comment inside
    $text = preg_replace('/<!--(.|\s)*?-->/', '', $text);

    // Add back in the paragraph (<p>) and line break (<br>) tags again, remove empty ones
    return apply_filters('the_content', $text);

That's it. I know there has to be better ways to do this. If you have suggestions, leave a comment!