#15: the_content

The the_content filter makes it possible to modify the content of a post, page or other post type. It is probably one of the most commonly-used — and misused — filter hooks in the WordPress code base.

Misuse of the_content is rampant largely due to the geography of a post’s content on the page. Developers want something to show up at the end of the post so sometimes they’ll use this hook to accomplish that placement. Unfortunately, whatever it is they’re hooking onto the beginning or end of the_content often has little or nothing to do with the post itself.

It’s one of those filters where you can look to ‘how Core does it’ to really see its intended purpose. Out of the box, Core filters the_content in about 10 different places. This is to accomplish much of the behind-the-scenes post cleanup users never really see, which include:

  • oEmbed handling
  • converting smilies to images
  • removing unwanted characters
  • auto-adding paragraph tags
  • processing shortcodes
  • and more

In all such cases, Core filters the post content itself, but doesn’t tack on unrelated stuff.

the_content is evaluated in:

It accepts a single argument, a string containing the post’s content.

Example:

Let’s say you’re one of those people who just can’t get out of the habit of using two spaces after periods and you’ve been writing on your blog for years. The following will filter the_content to convert those pesky double spaces to singles.

View the code example on Gist.

Have a suggested improvement? You can fork the Gist and comment back with the link. If all is agreeable, I’ll merge in your changes. Crowd-sourced documentation FTW!

3 thoughts on “#15: the_content

  1. I have to admit that I have been guilty of using the_content to tack something onto the end of the post. Actually, I did that just the other day. But before I did, I searched to see if there was any such thing as an “after_post_content” hook, but I couldn’t find anything like that. Do you know of any other theme independent way(s) of appending content to a post?

    • There isn’t yet a great solution for plugins to accomplish something like this without filtering on the_content. Theme authors on the other hand, should just put whatever it is they want to add on into the template, or add their own hook that falls outside the post loop.

      I agree that there should be more hooks along the lines of after_post_content, and if you’re interested in joining the discussion, there’s a Trac ticket for theme hooks: http://core.trac.wordpress.org/ticket/21506

Leave a Reply

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