You can use the has_post_thumbnail
function to retrieve the post thumbnail by post ID in WordPress. Here’s an example code snippet:
<?php
$post_id = 123; // Replace 123 with your post ID
if (has_post_thumbnail($post_id)) {
$thumbnail_id = get_post_thumbnail_id($post_id);
$thumbnail_url = wp_get_attachment_image_src($thumbnail_id, 'thumbnail');
// Display the thumbnail image
echo '<img src="' . $thumbnail_url[0] . '" alt="Thumbnail">';
}
?>
In the above code, replace 123
with the actual post ID you want to retrieve the thumbnail for. The has_post_thumbnail()
function checks if the post has a thumbnail, get_post_thumbnail_id()
retrieves the ID of the thumbnail, and wp_get_attachment_image_src()
returns the thumbnail URL based on the attachment ID and the desired image size (in this case, ‘thumbnail’).
You can adjust the wp_get_attachment_image_src()
parameters to specify different image sizes such as ‘medium’, ‘large’, or a custom image size registered in your theme.