It is a general requirement while working with wordpress. We need the content of a post or page with the use of its “ID”. Sometimes we have “post id” and we need to fetch the content of that post. It is very simple, as we know that $post is having the information of a post or page globally. Just put the below mentioned code to fetch the content of post of page in raw format :

<?php 

$post_id = '52'; //where 52 is the id of post or page 
$required_post = get_post($post_id); // getting all information of that post 
$title = $required_post->post_title; // get the post title 
$content = $required_post->post_content; //get the post content
?>
<h3><?php echo $title; ?></h3>
<p><?php echo $content; ?></p>

In the above code you can get the post title and content of the post separately and able to put them as per your required html. But the above code will provide you the raw content which is unfiltered and not having the formatting as default wordpress pages and posts content have.

content
Get Post content with formatting :

Here we are explaining the scenario where we have the post or page id and want to fetch their content without loosing the formatting as they have. Use the below mentioned code :


<?php 

$post_id = '52'; //where 52 is the id of post or page 
$required_post = get_post($post_id); // getting all information of that post 
$content = $required_post->post_content; //get the post content
$content = apply_filters('the_content', $content); //using the_content hook 
$formatted_content = str_replace(']]>', ']]&gt;', $content);
echo $formatted_content;

?>

This code will work as per your expectations. It will have all the formatting as you have set for them in admin post or page. This content will have all of them if we set in admin :

  • Added paragraphs works fine
  • Image caption in wordpress content will show perfect
  • Image alignment will be perfect
  • Short code for slider, contact form and also other will work as expected.

Because we have applied the filters after fetching the content from database. So, use it as per your requirements. You can use it for fetching content for pages and post both. Just pass the post or page ID and get the content of your choice.

Hope this will help someone.