WordPress – Get featured image – the_post_thumbnail

If you are creating a custom theme in WordPress. Then, this is the most useful article for you. There are lots of time when you stuck with this issue “How to get the featured image”. I will explain you how to do this easily.

Step 1: To enable the featured image support, you need to add the same in your functions.php file. The explanation is provided at “Add Featured Image support in Custom WordPress Theme

Step 2: When you create a new post, add the featured image in the “Featured Image” section of your post. Because, you won’t get anything if the featured post is not assigned.

Step 3: To access the featured image in your theme, you can use two functions i.e. the_post_thumbnail() and get_the_post_thumbnail().

the_post_thumbnail()
the_post_thumbnail() function is used to display the post thumbnail if you are in the loop. It prints the image directly. You can pass size & attributes parameters in the function.
the_post_thumbnail( $size, $attr )
$size (optional) => WordPress have various pre-defined sizes for uploaded featured image. The default value is “post-thumbnail”
$attr (optional) => Query string or array of attributes

the_post_thumbnail();               // default -> 'post-thumbnail'

the_post_thumbnail( 'thumbnail' );  // Thumbnail (default 150px x 150px max)
the_post_thumbnail( 'medium' );     // Medium resolution (default 300px x 300px max)
the_post_thumbnail( 'large' );      // Large resolution (default 640px x 640px max)
the_post_thumbnail( 'full' );       // Full resolution (original size uploaded)

the_post_thumbnail( array(100, 100) );  // Other resolutions as you want

You can even register new post thumbnail sizes of your choice using the function add_image_size()

get_the_post_thumbnail()
get_the_post_thumbnail() function is used to display the post thumbnail even if you are outside of the loop. It returns the image tag as a variable. You can pass post id, size & attributes parameters in the function.
get_the_post_thumbnail( $post, $size, $attr )
$post (optional) => Post ID or Post Object. Default value is null. If null is passed, then global $post is used
$size (optional) => WordPress have various pre-defined sizes for uploaded featured image. The default value is “post-thumbnail”
$attr (optional) => Query string or array of attributes

Example of $attr parameter is:
array( 'class' => 'alignleft', 'title' => 'WhateverTitle')

Let me know if you have any query in comments.

Leave a Reply

Your email address will not be published. Required fields are marked *