WP-Mix

A fresh mix of code snippets and tutorials

Disable extra p tags in WP shortcodes

When WordPress processes shortcodes, it first passes the content through its wpautop() function to convert line breaks to <p> or <br> tags. This order of processing can lead to unwanted paragraph and breaks scattered throughout your shortcode content. This post provides a simple way to prevent this from happening, so you can keep your shortcode content nice and clean.

Disable auto-formatting in shortcode content

The first step in disabling extra paragraph and break tags in shortcode content is to disable auto-formatting in shortcode content. We can do that by adding the following code via the theme’s functions.php file:

remove_filter('the_content', 'wpautop');
add_filter('the_content', 'wpautop', 12);

Here we remove wpautop() and then replace it with a lower priority, 12. This effectively reverses the order of execution for WP shortcodes. With this code in place, the shortcode content is passed through wpautop() after it has been processed. End result: no more <p> and <br> tags littering your otherwise pristine code.

Enable auto-formatting in shortcode content

The potential downside to this technique is that wpautop() won’t be able to auto-convert any line breaks to paragraphs or breaks. That means that your shortcode content will be squeaky clean, but without any automatically added markup or formatting.

So you can either add your own markup and call it good, or if you want the auto-formatting markup and such provided by wpautop(), you can call it from within your shortcode. For example:

function shapeSpace_example_shortcode($atts, $content = null) {
	$content = wpautop(trim($content));
	return $content;
}
add_shortcode('example', 'shapeSpace_example_shortcode');

And that’s how you disable unwanted <p> and <br> tags in your shortcode content. Here is a quick summary to really drive it home:

  1. First, change the priority of auto-formatting so it happens after shortcodes are processed.
  2. Then, if you want to enable WP’s auto-formatting (but without any unwanted tags), call wpautop() from within your shortcode.

Bada bing, bada boom.

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress