If you have ever done WordPress programming, you may have come across the need to get WordPress post content by post ID. There are several scenarios where such a situation may arise for instance when trying to retrieve content from a WordPress database to publish across different publishing channels independent of your WordPress installation.
The good news is that there are several ways to get WordPress post content by post ID. In this write up, we’ll go over the two very simple, easy and quick methods used by expert WordPress programmers to get WordPress post content by post id.
The goal here is to enable you quickly and easily retrieve the contents of a particular WordPress post using the post’s ID. So first, you need to know the post’s ID or if you’re doing so programmatically, execute the appropriate queries that will look up the WordPress post’s id and then pass the value appropriately as indicated below.
This is a one liner – short and simple. Use the following code:
$my_post_content = apply_filters('the_content', get_post_field('post_content', $my_post_id));
// The above one liner simply pulls the content by calling
// the get_post_field() function and passing to it the
// $my_post_id value and the ‘post_content’ hook. Using the
// $my_post_id the function retrieves the appropriate post
// via the ‘post_content’ hook. Then the apply_filters()
// is called to filter the retrieved content using the
// ‘the_content’ hook.
// Optionally, you can add the above line to print or display
// the content
Another simple step-by-step approach to get WordPress post content by post id:
$my_post_id = 12;
// The above line assigns the post or page id to the $my_post_id variable
$my_post = get_post($my_post_id);
// The above retrieves all data pertaining to the page or post with id $my_post_id
$my_post_content = $my_post->post_content
// The above line gets the content of the post (i.e $my_post)
$my_post_content = apply_filters('the_content', $my_post_content);
// The above line filters the retrieved content using the ‘the_content’ hook.
$my_formatted_content = str_replace(']]>', ']]>', $my_post_content);
// The above line formats the filtered content so that it retains all formatting set in the WordPress admin.
2 Simple Methods To Get WordPress Post Content By Post ID
We hope you found this write up 2 Simple Methods To Get WordPress Post Content By Post ID useful. If you’re looking for a reliable and super-fast WordPress hosting server to host your WordPress CMS applications, email us at firstname.lastname@example.org for assistance.