the_content

How to Display Properly Formatted Content From a $post Object in WordPress

May 21, 2009   ·   By   ·   10 Comments   ·   Posted in Functions, Wordpress, Writing Plugins

Occasionally, I’ll run into a situation where I need to call a post specifically using the get_post() function.  get_post() returns a Post object, with a number of member variables – the one that stores the actual content of the post being post_content.

However, if you try just echoing $post->post_content, you’ll get completely unformatted text – which is frustrating, because WordPress uses a great visual text editor on the backend – it’s a shame to not take advantage of it.  Fortunately, WordPress provides a filter to display the text just as it would be displayed in the the_content() function inside the loop.  Here’s how it works:

To get the content formatted properly, we need to apply a filter (which is different from adding a filter – here, we’re registering it so that other filter functions can modify it before it’s displayed).


apply_filters('the_content', $post->post_content);

So, we’re just applying the the_content filter to the $post->post_content variable.  Doing so means that any plugin which adds a filter function to the_content like this:


add_filter('the_content', 'my_content_manipulator');

function my_content_manipulator($content){

//do stuff here

return $content;

}

will be applied to your variable.  Fortunately, it also means that the WordPress core functions which format the post content correctly can also work on it.

Need more info about the $post object? Check out this post: .