Solution to WordPress adding br and p tags around shortcodes

The Problem:

Sometimes I find stray p or br tags appearing inside a block of content that I’ve enclosed in shortcodes and this can mess up the layout by adding extra spacing where I don’t want it. It occurs because of the default order in which WordPress processes your content – wpautop (the function which converts line breaks to p or br tags) is run before the shortcodes are processed.

The Solution:

  1. Change the execution priority of wpautop so that it executes after the shotcodes are processed instead of before. Add this in your functions.php file:

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

  2. Now there will be no extra p or br tags added inside your shortcode block. In fact there will not be any automatic conversion of line breaks to p and/or br tags at all. So if you want the legitimate line breaks to convert to p and br tags, you will need to run wpautop from inside your shortcode function, e.g.:

    function bio_shortcode($atts, $content = null) {
       $content = wpautop(trim($content));
       return '<div class="bio">' . $content . '</div>';
    }
    add_shortcode('bio', 'bio_shortcode');

23 Responses to Solution to WordPress adding br and p tags around shortcodes

Leave a Reply

Your email address will not be published.

© 2020 Stellar Web Works Ltd.