Been struggling over the last day or so to stop WordPress wrapping p tags around a shortcode. I’m using Arnan de Gans Events plugin on a WordPress site for a client. One of the pages just includes this shortcode:
[events_show]
This shows a list of events. I’ve configured the plugin so each event is in its own div. And it all works fine, except WordPress insists on wrapping the whole thing in a couple of p tags, making the code invalid, producing this:
<p><div class="event>.........</div></p>
Irritating. The WP shortcode API site says “wpautop recognizes shortcode syntax and will attempt not to wrap p or br tags around shortcodes that stand alone on a line by themselves”. Nooooo.
I finally solved this by adding the following to my functions.php file:
function simonbattersby_shortcode_format($content){ $content = preg_replace('/(<p>)\s*(<div)/','<div',$content); $content = preg_replace('/(<\/div>)\s*(<\/p>)/', '</div>', $content); return $content; } add_filter('the_content','simonbattersby_shortcode_format',11);
Points to note – the filter needs to be set with priority 11 (or higher) because otherwise the shortcode won’t have produced its output, and it’ll have no effect. All the preg_replace
lines are doing is looking for a <p>
tag followed by <div>
, with any number of whitespaces between them, and replacing with just a <div>
tag. Brute force, inelegant, but it works, and I couldn’t find any other way….