How to prevent WordPress from adding <p> tags in page content

One of the things that initially made WordPress into the hugely popular CMS that it is today was its ease of use.

But some of the conveniences that WordPress comes with is not always desirable, like the fact that WordPress automatically adds <p> (paragraph) tags to content.

Here on Templ.io for example, we don’t use any page builder or WYSIWYG to construct our pages. Instead, all of our pages are made up of very precise and manually written HTML markup, and in our case it was a pain in the *** when WP automatically added <p> all over our page content, which sometimes screwed up our page designs completely.

Luckily, we managed to disable this functionality by adding a small code snippet to our theme’s functions.php file.

We wanted to keep the automatically added <p> tags in our blog posts, but remove them from our pages. Here is the code that we use:

// Prevent WP from adding <p> tags on pages
function disable_wp_auto_p( $content ) {
  if ( is_singular( 'page' ) ) {
    remove_filter( 'the_content', 'wpautop' );
    remove_filter( 'the_excerpt', 'wpautop' );
  }
  return $content;
}
add_filter( 'the_content', 'disable_wp_auto_p', 0 );

If you instead wish to prevent WordPress from adding <p> tags on both pages, posts and all other post types, you can simply remove the if ( is_singular( 'page' ) ) statement, like this:

// Prevent WP from adding <p> tags on all post types
function disable_wp_auto_p( $content ) {
  remove_filter( 'the_content', 'wpautop' );
  remove_filter( 'the_excerpt', 'wpautop' );
  return $content;
}
add_filter( 'the_content', 'disable_wp_auto_p', 0 );

If you want to prevent WP from adding <p> tags to any other post type, you can simply replace page in if ( is_singular( 'page' ) ) with your post type of choice.

Smart, huh?

Have you found any other smart way to apply this code, or if you have some other neat little WordPress tweak to share? Please feel free to leave a comment below.