153

How can I get WordPress post content by post id?

192

Simple as it gets

$my_postid = 12;//This is page id or post id
$content_post = get_post($my_postid);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
| improve this answer | |
  • 89
    Shorthand for specific field: $content = get_post_field('post_content', $my_postid); – Rarst Feb 17 '11 at 21:39
  • 5
    @Bainternet I'm just curious here... what is the part $content = str_replace(']]>', ']]>', $content); do? what's the purpose of it there? – Average Joe Nov 4 '13 at 11:02
  • 2
    @AverageJoe its basic search and replace. When using the_content() the content is filtered. Since in the above example the content was directly retrieved, the author has used the search and replace to make it safe. – Harish Chouhan Mar 18 '14 at 9:21
  • 3
    maybe you also need do_shortcode() like $content = do_shortcode(get_post_field('post_content', $my_postid)); – cyptus Mar 9 '18 at 13:47
  • Is there anyway to preserve the "more_link"? – user2128576 Jul 5 '18 at 1:46
139
echo get_post_field('post_content', $post_id);
| improve this answer | |
  • 63
    better to do it like echo apply_filters('the_content', get_post_field('post_content', $post_id));. For example when using qTranslate, your solution would not be enough. – Karel Attl Jan 17 '13 at 7:10
  • 5
    This is the best answer if the scope is to get the post content as it is in the WordPress edit page. – mcont Aug 8 '14 at 13:21
  • 1
    Without the code from @KarelAttl line breaks where missing. With the apply_filters code it worked perfectly. – Alexander Taubenkorb Sep 23 '15 at 12:23
  • 2
    apply_filters is a good option, but wasn't right for my current purpose. It's good to have both options. – KnightHawk Nov 5 '15 at 18:12
31

Another way to get a WordPress post content by post id is:

$content = apply_filters('the_content', get_post_field('post_content', $my_postid));

To complete this answer I have also added method 01 and method 02 to this answer.

Method 01 (credit goes to bainternet):

$content_post = get_post($my_postid);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);

Method 02 (credit goes to realmag777):

$content = get_post_field('post_content', $my_postid);

Method 03:

$content = apply_filters('the_content', get_post_field('post_content', $my_postid));

Read the What is the best / efficient way to get WordPress content by post id and why? question to get an idea about which one you should use from the above three.

| improve this answer | |
-1

If you need more than one post, use get_posts(). It leaves the main query alone and returns an array of posts that's easy to loop over.

| improve this answer | |

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