The get_the_post_thumbnail() WordPress function

The get_the_post_thumbnail() WordPress function will allow you to get the featured image and display it using your theme or plugin. In this article, we will teach you how to use the get_the_post_thumbnail() function to display featured images anywhere you want to.

Note: To use the get_the_post_thumbnail() function, you will need to enable support for it within your theme.

To enable support for the get_the_post_thumbnail() function, include the following in your theme's functions.php file:

add_theme_support( 'post-thumbnails' );

Basic usage

<?php echo get_the_post_thumbnail( $post_id, $size, $attr ); ?>

In the above code, we are simply displaying the featured image of a post based on the parameters we have defined. Below, you will see the various parameters that can be defined within the get_the_post_thumbnail() function.

Parameters

$post_id: This is an optional parameter in which you can define the post ID of the post that you will be obtaining the featured image from. If this is not defined, it will display the featured image from the current post that you are viewing.

$size: This is an optional parameter that can be used to determine the size that the featured image is displayed. You may define either a string or an array with the dimensions.

Pre-defined sizes:

thumbnail

medium

large

full

Custom sizes:

To define a custom size, simply define it within an array, for example:

get_the_post_thumbnail($post_id, array(100,100), $attr );

As you can see from the above code, the image size is 100x100.

$attr: This is an optional parameter in which you may use an array to define additional attributes such as the class, alt text, title, etc. This would look something like the following: