Stop WordPress adding <p> tags in code elements

WordPress has a tendency to sprinkle an abundance of p tags in your blog posts wherever you have lots of spaces between paragraphs. In most cases it is exactly what you want. You want the paragraph spacing to be nice and consistent. But there are times it works against you. I tend to put all code extracts in my blog posts in code tags. I use css to style any code that should be a block. The problem is code tends to have consecutive line breaks. Wodpress goes and separates the codeblock where it finds more than one line-break and wraps them in a p element.

So, what do you do? Well, the solution is the wp-includes/formatting.php in a function called wpautop(). Apart from finding a whole bunch of pee jokes in this function (with variable names like pee and tinkle), you will see that it cleans up line breaks and replaces a lot of them with P tags. You will also see that pre tags are treated specially.

So basically what I did is copied the function that processes pre elements, and had the new function handle code tags. The new function looks like this:


function clean_code($matches) {
if ( is_array($matches) )
$text = $matches[1] . $matches[2] . "</code>";
else
$text = $matches;

$text = str_replace('<br />', '', $text);
$text = str_replace('<p>', "\n", $text);
$text = str_replace('</p>', '', $text);

return $text;
}

I also added a call to this function for regex matches to <code, in the wpautop() function just after the pre handling code..


if (strpos($pee, '<code') !== false)
$pee = preg_replace_callback('!(<code[^>]*>)(.*?)</code>!is', 'clean_code', $pee );

You probably don’t want to make this change in the formatting.php file itself, as whenever you upgrade WordPress, you’ll need to port this change over. You can add it to your theme by clopying the wpautop() function into your functions.php file – with a new name of course, and making the changes in that function.

You can then add the following to unregister the stock wpautop() function and use your one:


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

Author: Musaul Karim

Software Engineer, Hobbyist Photographer, and a bit of a gadget geek.

Leave a Reply

Your email address will not be published. Required fields are marked *