Get Content by ID

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;
}

Comments

  1. User Avatar
    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. User Avatar
    Justin Tallant
    Permalink to comment#

    echo get_post_field(‘post_content’, $post_id);

    • User Avatar
      Carlos Sanz
      Permalink to comment#

      Nice!

    • User Avatar
      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. User Avatar
    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. User Avatar
    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. User Avatar
    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!

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag