Skip to content

Instantly share code, notes, and snippets.

@illucent
Forked from jlengstorf/README.md
Created April 15, 2014 22:52
Show Gist options
  • Select an option

  • Save illucent/10785819 to your computer and use it in GitHub Desktop.

Select an option

Save illucent/10785819 to your computer and use it in GitHub Desktop.

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 <[email protected]>
*/
function copter_remove_crappy_markup( $string )
{
$patterns = array(
'#^\s*</p>#',
'#<p>\s*$#'
);
return preg_replace($patterns, '', $string);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment