WordPress offers quite a friendly hybrid WYSIWYG / HTML editor that makes publishing easy even for those with no HTML experience. One of the ways it accomplishes this is through a function called
wpautop. This runs on
the_content as the page is drawn to insert
<br/> tags as needed. By inserting them dynamically like this it prevents code creeping in to the editor and leading to potential confusion / corruption. However, it can sometimes lead to unexpected results – especially when combined with shortcodes.
The problem with wpautop and Shortcodes
While WordPress does try to detect shortcodes and prevent unexpected behaviours, I have found it still occurs and often ends up with the shortcode itself being wrapped in
<p> tags – this isn’t usually a major problem, but creates messy code which just bugs me. Also, quite a lot of plugins, and some badly designed themes apparently, will trigger
wpautop inside shortcodes. Recently I found that one of my favourite plugins – Simple Fields – does this on it’s textareas which was causing a shortcode inserting their content to be prepended with a
<br/>. In this case it was a particular problem as the shortcode in question was generating columns and the unexpected tag was breaking the layout.
It is possible to completely turn off
wpautop by adding the following line to your function.php file (or using one of many plugins):
remove_filter( 'the_content', 'wpautop' );
This works great is all your editors are tech savvy and happy writing markup by hand, but otherwise it is taking a sledgehammer to crack a nut and will likely just lead to unformatted text. Even if you use the visual editor, no tags are inserted automatically when you hit Return.
However we are half way there. The root cause isn’t that
wpautop is running, but that it is being run on
Luckily WordPress provides a handy way to set the priority of functions. All we have to do is remove
wpautop, then re-add it and define the priority as something greater than the default (10) that is also greater than the priority for
do_shortcode, which is 11.
Adding the following code to your functions.php will make sure that it runs after everything else, keeping the usability but stopping the random insertions:
remove_filter( 'the_content', 'wpautop' ); add_filter( 'the_content', 'wpautop' , 99);
You may get unexpected behaviours depending on what other plugins are doing / modifications have been made so you may have to tweak the priority to get everything running smoothly.