Stray closing paragraph tag when using shortcodes

This is frustrating issue as I can’t depend on the content editors to be savvy enough with WordPress / HTML to understand how the text they input will be parsed…

–EDIT–

Having thought of this a bit more I have reconsidered my earlier answer. HTML5+ comes with the Tidy extension, if you are able to use this on your server then the following will work:

function cleanUpAutoP($content)
    {
        $tidy = new Tidy();
        // Switch out the encoding an doctype in $tidyArgs to suit your use case
        // 'show-body-only' HTML to be parsed as a fragment
        // rather than a whole document
        $tidyArgs = array(  'doctype' => 'html',
                            'input-encoding' => 'utf8',
                            'output-encoding' => 'utf8',
                            'show-body-only' => true
                    );
        // Return the repaired string
        return $tidy->repairString($content, $tidyArgs);
    }

This way you can enjoy all the benefits of sweet, sweet P tags without the fear that wpautop will have messed something up. Further options for $tidyArgs can be seen in the documentation.

If Tidy is not available for whatever reason this should still work:

function cleanUpAutoP($content) {

    // Replace all OPENING paragraph tags with <br /><br />
    $content = preg_replace('/<p[^>]*>/', '<br /><br />', $content);

    // Remove all CLOSING p tags
    $content = str_replace('</p>', '', $content);


    return $content;
}

The obvious drawback of the latter method that I cannot apply styles to p tags in shortcodes, but until a better solution comes along, or the issue is fixed in WordPress, it will do!

Leave a Comment