All Posts by Email, Once a Week

Media Temple logo

CSS-Tricks is brought to you in part by Media Temple, the web hosting that we both use and recommend.

Get Content by ID

Last updated on:

Apparently there is no succinct WordPress function for just returning the content of a particular page by the ID of that page. This is that.

function get_the_content_by_id($post_id) {
  $page_data = get_page($post_id);
  if ($page_data) {
    return $page_data->post_content;
  }
  else return false;
}

Reference URL

Comments

  1. Cameron Spear
    Permalink to comment#

    You might consider changing the title to mention WordPress. I was thinking that you made a new blog post about how to get content of an HTML element by ID, which, ya know, is pretty complicated in and of itself…

  2. Justin Tallant
    Permalink to comment#

    echo get_post_field(‘post_content’, $post_id);

    • Carlos Sanz
      Permalink to comment#

      Nice!

    • Michael Fields
      Permalink to comment#

      One of my favorite WordPress functions! Very handy in attachment/images templates when your are displaying data from the parent post.

  3. Andrew Staffell
    Permalink to comment#

    If you want the content formatted exactly as the_content() would be (auto paragraphs and curly quotes and so on), line 4 should be:

    return apply_filters('the_content', $page_data->post_content);
  4. irfan
    Permalink to comment#

    function get_the_content_by_id($post_id) {
    $page_data = get_page($post_id);
    if ($page_data) {
    $content = $page_data->post_content;
    return $content = apply_filters(‘the_content’, $content);
    }
    else return false;
    }

  5. Spencer
    Permalink to comment#

    Just found this to be very useful and wanted to say thanks! I did notice that get_page is now depreciated. I’m using wordpress version 4.4.1 and I updated it with get_post();

    Cheers!

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed