Getting the Featured Image of a Post in WordPress using get_the_post_thumbnail

The WordPress get_the_post_thumbnail function retrieves the post thumbnail (also known as featured image) for the current post. This function can be useful for displaying the post thumbnail in a custom location within a WordPress theme or plugin.

By using get_the_post_thumbnail, developers can easily access and display the post thumbnail without having to manually retrieve and output the image URL or HTML markup.

Parameters accepted by the get_the_post_thumbnail function

  • $post (int/WP_Post), optional. Default value: null. Description: Post ID or WP_Post object. Default is global $post.
  • $size (string/int[]), optional. Default value: ‘post-thumbnail’. Description: Image size. Accepts any registered image size name, or an array of width and height values in pixels (in that order). Default ‘post-thumbnail’.
  • $attr (string/array), optional. Default value: ”. Description: Query string or array of attributes.

Value returned by the get_the_post_thumbnail function

The function returns a string which represents the post thumbnail image tag.

Examples

How to get the post thumbnail URL

$thumbnail_url = get_the_post_thumbnail_url( $post_id, 'thumbnail' );
if ( $thumbnail_url ) {
 echo '<img src="' . $thumbnail_url . '">';
}

This code snippet uses the get_the_post_thumbnail_url function to retrieve the URL of the post’s thumbnail image. If the URL exists, it then outputs an <img> tag with the thumbnail URL as the source.

How to get the post thumbnail with a custom size

$thumbnail = get_the_post_thumbnail( $post_id, array( 200, 200 ) );
if ( $thumbnail ) {
 echo $thumbnail;
}

This code snippet uses the get_the_post_thumbnail function to retrieve the post’s thumbnail image with a custom size of 200×200 pixels. If the thumbnail exists, it then outputs the thumbnail image.

How to get the post thumbnail with a fallback image

$thumbnail = get_the_post_thumbnail( $post_id, 'medium' );
if ( $thumbnail ) {
 echo $thumbnail;
} else {
 echo '<img src="fallback.jpg">';
}

This code snippet uses the get_the_post_thumbnail function to retrieve the post’s thumbnail image with a medium size. If the thumbnail exists, it then outputs the thumbnail image. If the thumbnail does not exist, it outputs a fallback image with the source “fallback.jpg”.

Conclusion

In conclusion, the get_the_post_thumbnail function is an effective feature for retrieving and displaying post thumbnails in WordPress. It offers a wide range of parameters to customize the output, making it a versatile and essential function for developers and designers. By understanding how to use this function effectively, you can enhance the visual appeal of your website and improve the user experience for your audience.

Related WordPress Functions