Skip to content

Instantly share code, notes, and snippets.

@jlengstorf
Last active September 10, 2018 01:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jlengstorf/5370457 to your computer and use it in GitHub Desktop.
Save jlengstorf/5370457 to your computer and use it in GitHub Desktop.
Removes the junk that wpautop adds to shortcodes in WordPress.

Remove Crappy Markup from WordPress Shortcodes

When using shortcodes in WordPress like so:

[shortcode]

Content goes here...

[/shortcode]

And assuming that the shortcode wraps your content with another element, sort of like this:

function my_shortcode( $attr, $content )
{
    return '<div class="my_shortcode">' . $content . '</div>';
}
add_shortcode('shortcode', 'my_shortcode');

The built-in WordPress wpautop filter will add junk markup to your output:

<div class="my_shortcode">
</p>
<p>Content goes here...</p>
<p>
</div>

Adding copter_remove_crappy_markup() to the shorcode will clean up the output:

function my_shortcode( $attr, $content )
{
    $clean = copter_remove_crappy_markup($content);
    return '<div class="my_shortcode">' . $clean . '</div>';
}
add_shortcode('shortcode', 'my_shortcode');

Resulting in:

<div class="my_shortcode">
<p>Content goes here...</p>
</div>
<?php
/**
* Removes mismatched </p> and <p> tags from the beginning and end of a snippet.
*
* @author Jason Lengstorf <jason@copterlabs.com>
*/
function copter_remove_crappy_markup( $string )
{
$patterns = array(
'#^\s*</p>#',
'#<p>\s*$#'
);
return preg_replace($patterns, '', $string);
}
@karlschwaier
Copy link

Thanks for your function. I have used it until I read about WordPress' built-in filter shortcode_unautop on http://www.paulund.co.uk/remove-line-breaks-in-shortcodes. I guess that's a better way to clean up the markup.

@jlengstorf
Copy link
Author

@karlschwaier That's an interesting approach — more or less the same as mine, just with a far more complex regex. Nice to know that WP has that built in, though. I was unaware they'd handled that already. Thanks for the heads up!

@aliciaj
Copy link

aliciaj commented Jul 11, 2018

How did you create the pattern for the <p> tags, I would like to use this function but also include
I tried a regular regex pattern, doesn't work.
'#^\s*</p># equivelent for <br>

@petertwise
Copy link

Ummmm, btw, what's up with the use of the variable names $pee and $pee_parts in WP core files in wp-includes/formatting.php

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