In this tutorial, we will learn how to retrieve and display the featured image for a post in WordPress using PHP. The featured image is a special image that is chosen by the post author to represent the post. It is often used as the main image for the post when it is displayed on the blog or website.

This PHP code retrieves the featured image for a post and displays it as an image.

<?php $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>

<img src="<?php echo $feat_image; ?>" width="80" height="100" />

The function wp_get_attachment_url() is used to retrieve the URL for the featured image of the post. This function takes in the post thumbnail ID as an argument, which is obtained using the get_post_thumbnail_id() function. This function also takes in the post ID as an argument, which is passed using the $post->ID variable.

The URL for the featured image is then stored in the $feat_image variable. This variable is then used in the src attribute of an <img> element to display the featured image on the page. The width and height of the image can also be specified using the width and height attributes of the <img> element.

In addition to retrieving and displaying the featured image for a post, we will also learn how to handle the case where a post does not have a featured image. In this case, we can display a default image instead. We can accomplish this using an if statement to check if the featured image URL is set, and if it is not, we can display the default image instead.

This PHP code checks if the post has a featured image, and if it does, it displays the featured image. If the post does not have a featured image, it displays a default image instead.

check below code:

<?php $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>

<?php if($feat_image) {?>
<img src="<?php echo $feat_image; ?>" width="80" height="100" />
<?php } else {?>
<img src="default.jpg" width="80" height="100" />
<?php } ?>

The $feat_image variable is first defined using the wp_get_attachment_url() function as in the previous example. This function retrieves the URL for the featured image of the post, given the post thumbnail ID which is obtained using the get_post_thumbnail_id() function and the post ID which is passed using the $post->ID variable.

Next, an if statement is used to check if the $feat_image variable is set. If it is set (i.e., if the post has a featured image), the featured image is displayed using an <img> element with the src attribute set to the value of the $feat_image variable. If the $feat_image variable is not set (i.e., if the post does not have a featured image), the default image is displayed instead using an <img> element with the src attribute set to the URL of the default image.

With these techniques, we will be able to easily retrieve and display the featured image for a post in WordPress.