Remove wpautop() on Pages

The Problem

I wanted to be able to selectively enable and disable the built-in WordPress function wpautop() ‐ On for blog posts and off for pages. And if I want to override either of those defaults, I should be able to do that with Custom Fields for the post or page.

But.. why?

When I’m creating a Page (as opposed to a Post) I spend more time carefully crafting the HTML and CSS for it. wpautop() can get in the way sometimes and make a mess of things.

Disabling it altogether is easy, but I’ve found that keeping it around as an option for blog posts can be handy. Blog posts generally don’t have as much formatting as WP pages and in those cases I just want to focus on my writing rather than the code.

The Solution

Add a filter function to functions.php that disables wpautop() on Pages and also on any item that has a Custom Field set of “remove_wpautop”

Add this to your theme’s functions.php file at the end:

/**
 * Disable wpautop
 *    1] On Pages (if not overriden in the custom fields), OR
 *    2] On Posts thave have a custom field of 'disable_wpautop'
 *
 *    Author: Jon Wood - http://windsorwebdeveloper.com
 */
function disable_wpautop_on_pages($content)
{

  $post_id = get_the_ID();

  //If it's a Page we remove wpautop by default, unless overriden
  if ( get_post_type() == 'page' ) {

    //check for the 'enable_wpautop' override in the Custom Fields
    if ( get_post_meta($post_id, 'enable_wpautop', true )) {
      return wpautop($content);
    }
    return $content;
  }
  
  //All other post types (blog posts or custom types) use wpautop
  //unless overriden with 'disable_wpautop'
  if ( get_post_meta($post_id, 'disable_wpautop', true )) {
    return $content;
  }  
  return wpautop($content);

}
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
add_filter( 'the_content', 'disable_wpautop_on_pages' );
add_filter( 'the_excerpt', 'disable_wpautop_on_pages' );

This code was inspired by this stackoverflow post and further expanded upon.

Cool, but what if you don’t want to always disable it on pages by default?

If you would rather explicitly define when it is turned off you can use the simplified version below. It will only disable wpautop() when “disable_wpautop” = true is listed as a custom field for the post or page.

function disable_wpautop($content)
{
  
  if ( get_post_meta(get_the_ID(), 'disable_wpautop', true )) {
    return $content;
  }  
  return wpautop($content);

}
remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );
add_filter( 'the_content', 'disable_wpautop' );
add_filter( 'the_excerpt', 'disable_wpautop' );
Jon Wood is a WordPress developer in Windsor, Ontario
God, I hate WordPress

Did this post save you time, frustration, or money?


Leave a Reply

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

Note: Comments are moderated. Please submit the form only once.