Thursday, February 09, 2012

Gotcha of the Day: Fighting with WordPress's wpautop

The great thing about WordPress is that it makes editing HTML so easy, my customers can manage their own content. The annoying thing about WordPress is that part of the brains behind this easy editing (wpautop) seemingly randomly inserts HTML in your page.

For example, I was trying to lay out HTML like this:

<img class='alignleft' src='...'/>
<h3>This is a title</h3>
This is some body text

Yet, wpautop decided it needed to insert a BR into this, which throws off the layout:

<img class='alignleft' src='...'/><br/>
<h3>This is a title</h3>
This is some body text

For a while I fought with wpautop, trying to put stuff all on the same line and such. But it was clearly a balancing act that wasn't going to work.

And then it hit me: why not just turn off wpautop?

Naturally, there's a plugin for that. But, I didn't want to turn it off for all posts. Just for the post that I would be maintaining and this particular client wouldn't be editing.

I added the following lines of code to a plugin that's part of the system and I was basically there:

function maybe_wpautop($content) {
  $post = get_post();
  $skip_autop = get_post_meta($post->ID, 'skip_autop', true);
  return $skip_autop ? $content : wpautop($content);
}

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

For any post I want to skip the wpautop functionality, I just add the custom field skip_autop.

Now I'm back on solid terms with WordPress. I can let my client continue to be the benefit of its magic, while this same magic no longer gets in my way.

3 comments:

  1. Anonymous4:23 PM

    And which plugin did you choose to add your function?

    ReplyDelete
  2. I didn't use a specific plugin. I had written some custom plugins, and tossed my code at the end of one of them.

    ReplyDelete
  3. Here is a good Plugin for this Problem: http://www.bake-the-web.de/2012/03/22/no-wpautop/

    In the plugin-options you can decide where you want to disable wpautop. In the Excerpt, the Content or both.

    ReplyDelete

LinkWithin

Related Posts with Thumbnails