When customizing a WordPress theme, you may need to display specific posts by their ID rather than using standard loops. This guide explains how to retrieve and display posts by ID using WordPress core functions.
Retrieve a Single Post by ID
Use the get_post() function to fetch a post object by its ID. You can then access its properties like title and content.
<?php
$post_id = 1; // The post ID to retrieve
$post = get_post( $post_id );
if ( $post ) {
echo $post->post_title; // Output the title
echo $post->post_content; // Output the raw content
}
?>
Note: get_post() returns the raw, unfiltered content. To apply formatting filters (like shortcodes and auto‑paragraphs), use apply_filters( 'the_content', $post->post_content ).
Retrieve Multiple Posts by ID
To fetch several specific posts, use get_posts() with the 'include' parameter. This is useful for creating custom post lists.
<?php
$posts = get_posts( array(
'post_type' => 'any', // Retrieve any post type
'include' => array(1, 2, 3), // Array of post IDs
'numberposts' => 3 // Limit the number of posts
) );
if ( $posts ) :
foreach ( $posts as $post ) :
setup_postdata( $post );
?>
<li>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php
endforeach;
wp_reset_postdata(); // Reset global $post variable
endif;
?>
Key points:
- The
includeparameter accepts an array of post IDs. - Always call
wp_reset_postdata()after a custom loop to restore the main query’s post data. - Use
setup_postdata( $post )inside the loop to make template tags likethe_title()andthe_permalink()work correctly.
Important Considerations
- Ensure the post IDs exist and the posts are published; otherwise, nothing will be returned.
- For single‑post retrieval, check that
get_post()returns a valid object before accessing its properties. - When outputting content, remember that
post_contentis unfiltered. Applythe_contentfilters if you need formatted output. - Always reset post data after custom loops to avoid conflicts with subsequent queries.