Skip to Main Content

It’s pretty common for custom WordPress shortcode functions to end up with a bunch of empty or dangling <p> and </p> tags.  Rather than throwing the baby out with the bathwater (disabling wpautop), here’s a handy little function from AJ Clarke, WP Explorer Owner, that’ll clear your code right up.

Clean Up WordPress Shortcode Functions

Simply copy and paste the following code into your functions.php file or wherever your hold your shortcodes. This function will clean up the output of your shortcodes, which is especially important for nested shortcodes.

if( !function_exists('jdm_fix_shortcodes') ) {
    function jdm_fix_shortcodes($content){
        $array = array (
            '<p>[' => '[', 
            ']</p>' => ']', 
            ']<br />' => ']'
        );
        $content = strtr($content, $array);
        return $content;
        }
        add_filter('the_content', 'jdm_fix_shortcodes');
}

What it does:

Basically, this function filters all the content before it’s outputted and replaces any matched code with better code according to the following:

All instances of <p>[ are replaced with [– Removes opening paragraphs before shortcodes
All instances of ]</p> are replaced with ]– Removes closing p tags after shortcodes
All instances of ]<br /> are replaced with ]– Removes breaks after shortcodes

Again, credit where credit is due. This handy WordPress function originally appeared on the WP Explorer site.

Share the love:

Get Support

Nobody's perfect. If you need a little help, request support from the super-nerds at JDM Digital.

Any information you provide here will be kept confidential and only used for this purpose.

So we can follow-up.

The URL of the issue.

The more specific you can be, the better.

I am 100% robot

You're not a robot, are you? Sorry we have to ask.