What is the best / efficient way to get WordPress content by post id and why?

I just wanted to get WordPress content by post id. I found the following three ways to get WordPress content by post id. (All the following ways I found on this site.)

Method 01:

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

Method 02:

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

Method 03:

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

What is the best / efficient way from above there methods and why?

1 Answer
1

The methods you offer for comparison are pretty much the same, with minor API differences and whether the_content filters are applied.

Within the loop get_the_content() should typically be used, which properly handles split into pages and so on.

To retrieve raw content get_post_field() is generally suitable, but any further processing (such as the_content filters) heavily depends on specific purpose of retrieving content and what you are going to do with it.

PS take note that many extensions out there are dumb and variously break on the_content filter executed outside of loop / more than once.

Leave a Comment