How to Retrieve a WordPress Post by ID using PHP – Best Practices and Examples

please click here for more wordpress cource

To retrieve a WordPress post by ID, you can use the get post() function, which accepts the post ID as its only parameter. Here’s an example code snippet:

$post_id = 123; // replace with your post ID
$post = get_post($post_id);

if ($post) {
  // post found, do something with it
  echo $post->post_title;
  echo $post->post_content;
} else {
  // post not found
  echo 'Post not found.';

In this example, replace the value of $post_id with the ID of the post you want to retrieve. The get_post() function returns a post object if the post is found, or false if it’s not found. You can then check if the post object is not false to make sure the post was found before accessing its properties (such as post_title and post content).

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *