20

I'm trying to retrieve the post content of a specific post:

$post = get_post(/* id */);
$content = $post->post_content;

However, this retrieves the content with no line-breaks and omits all <p> tags.

What is the proper way to retrieve the post content without stripping the <p> tags (as it is shown on the post page or the post editor "Text" tab)?

30

Both answers so far are correct but a more thorough answer seems warranted.

If you use this:

$content = wpautop( $post->post_content );

you're applying the one function that adds paragraph tags to post content. wpautop() is one of many functions (including plugin functions at times) that hooks onto the_content, so if you do this:

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

you're getting the post content run through any filters on the_content which includes wpautop() by default.

Finally, if you're in the loop, you can just do this:

$content = apply_filters( 'the_content', get_the_content() );

which is essentially a wrapper for the second code snippet, but of course it's a little nicer looking. Update 1 Sep 2018: Revised based on comment. Props @timmb.

Generally, I'd say that the preferred "right way" to do this is from last to first since using a core WP function should enable more backwards compatibility (theoretically, at least). The only other decision to make then is whether you want to allow WordPress and plugins to also modify the post content. If that's the case, definitely use the 2nd or 3rd options.

  • 1
    I think this final solution is incorrect. From codex.wordpress.org/Function_Reference/get_the_content : "An important difference from the_content() is that get_the_content() does not pass the content through the 'the_content' filter." Would this not suggest the correct approach would be $content = apply_filters('the_content', get_the_content);? – Tim MB Sep 1 '17 at 11:00
7

Found the solution:

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

Second method to get post content with p tag is

echo wpautop( $post->post_content );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.