4

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?

4
  • 1
    I'd say the way with the least amount of code, function calls, and queries. What did you do to try and profile these? What are the results of your benchmarks? Did you account for oEmbeds and Shortcode in your content - does that matter? Where are you using this data after you gather it? You should supply better context to the question for a more useful answer.
    – jgraup
    Commented Nov 10, 2016 at 13:03
  • Also, I think I remember there being a few filters to run on the content - wordpress.stackexchange.com/a/245057/84219
    – jgraup
    Commented Nov 10, 2016 at 13:08
  • @jgraup I asked this question after writing a answer for this question (wordpress.stackexchange.com/questions/245661/…)
    – Ranuka
    Commented Nov 10, 2016 at 15:24
  • as @jgraup say, this question lacks context and "best" can be decided only in a specific context for anything which is not trivial Commented Nov 10, 2016 at 17:18

1 Answer 1

4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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