WordPress: Prevent auto tags in page content

If you make use of some basic mark-up in your WordPress page content, you may have encountered an issue where <br /> tags are appearing where they shouldn’t and are affecting your theme layout.

To prevent this happening but leave the auto conversion of double line-breaks into paragraph tags, I had a dig into the wpautop function that runs before the content is outputted to the screen.

This function accepts two parameters, the first is the content to be formatted and the second determines whether to convert remaining line breaks into <br /> tags.

Because the wpautop filter is automatically applied to the content, we first need to remove that by adding the following to our functions.php file:

remove_filter('the_content', 'wpautop');

Then we must apply the formatting function again but this time set the the second parameter to false and prevent the additional <br /> tags appearing.

function wpautopnobr($content) {
	return wpautop($content, false);
}
add_filter('the_content', 'wpautopnobr');

This can be customised further by checking to see if we are on a page rather than a post and only applying the formatting if that is the case. The required code in it’s entirety is as follows:

remove_filter('the_content', 'wpautop');
function wpautopnobr($content) {
	return wpautop($content, (is_page() ? true : false));
}
add_filter('the_content', 'wpautopnobr');

One Reply to “WordPress: Prevent auto tags in page content”

  1. Hi,

    What if I only want to stop WordPress from replacing line breaks with break tags between certain HTML tags?

    This is occuring even in TEXTAREA tags, so these break tags are actually showing on the page inside of text boxes. I would expect those to be off limits to filters since they are preformatted.

    Is there anyway to correct this, that you know of?

    Thank you.

Leave a Reply