Using WordPress ‘get_the_post_thumbnail()’ PHP function

The get_the_post_thumbnail() WordPress PHP function retrieves the post thumbnail.

Usage

get_the_post_thumbnail($post, $size, $attr)

Example:

Input:

echo get_the_post_thumbnail($post_id, 'medium', array('class' => 'alignleft'));

Output:
<img src="your-image-url" alt="Post Thumbnail" class="alignleft wp-post-image" width="300" height="200">

Parameters

  • $post (int|WP_Post) (Optional): Post ID or WP_Post object. Default is global $post.
  • $size (string|int) (Optional): 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): Query string or array of attributes. Default: ”.

More information

See WordPress Developer Resources: get_the_post_thumbnail()

Examples

Display post thumbnail with default size

This example displays the post thumbnail using the default ‘post-thumbnail’ size.

echo get_the_post_thumbnail($post_id);

Display post thumbnail with custom size

This example displays the post thumbnail using a custom size of 200×200 pixels.

echo get_the_post_thumbnail($post_id, array(200, 200));

Display post thumbnail with additional class

This example displays the post thumbnail with the ‘alignleft’ class added.

echo get_the_post_thumbnail($post_id, 'medium', array('class' => 'alignleft'));

Display post thumbnail with alt attribute

This example displays the post thumbnail with a custom alt attribute.

echo get_the_post_thumbnail($post_id, 'medium', array('alt' => 'Custom alt text'));

Display post thumbnail within a loop

This example displays the post thumbnail for each post within a loop.

if (have_posts()) :
    while (have_posts()) : the_post();
        echo get_the_post_thumbnail(get_the_ID(), 'medium');
    endwhile;
endif;