Luutaa Technologies - Developer Blog

How to get thumbnail image src attribute in wordpress

WordPress introduced Post Thumbnail feature in Version 2.9.  Thumbnail is an image that is chosen as the representative image for Posts, Pages or Custom Post Types.  This is especially useful for “magazine-style” themes where each post has an image according to wordpress .

To enable post thumbnail write this code in your theme functions.php file

if ( function_exists( 'add_theme_support' ) ) {
    add_theme_support( 'post-thumbnails' );
    set_post_thumbnail_size( 150, 150, true ); //default Post Thumbnail dimensions (cropped)

    // additional image sizes
    // delete the next line if you do not need additional image sizes
    add_image_size( 'category-thumb', 300, 9999 ); //300 pixels wide (and unlimited height)

More detailed information can be found at WordPress codex for Post Thumbnail.

Next, important thing is how to use post thumbnail in wordpress loop ? It is not a complex thing . We have to just check whether post thumbnail for current post exists or not, and if it exists display it .

Code for post thumbnail display :


$default_attr = array(
		'src'	=> $src,
		'class'	=> "attachment-$size",
		'alt'	=> trim(strip_tags( wp_postmeta->_wp_attachment_image_alt )),
		'title'	=> trim(strip_tags( $attachment->post_title )),

if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
    the_post_thumbnail($image_size , $default_attr);


As you can see first we checked whether the post thumbnail exists or not with


if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
   // write code for display here

then, to display the post thumbnail we have to write

the_post_thumbnail($image_size , $default_attr);

In the above code first attribute is image size which we can set in our functions.php.

Another attribute is the array of attributes like image class, alt tag,  title tag and src.

The only problem with this function is that it echo’s the whole html code for post thumbnail wrapped in <img /> .

So it is very difficult to get only the src of the post thumbnail. But as usual there is a way to get only the src of thumbnail image.

just write a line of code and you will get in return the array containing three values

  • thumbnail src
  • thumbnail width
  • thumbnail height

so just write

$thumbnail = wp_get_attachment_image_src ( get_post_thumbnail_id ( $post->ID ), $image_size);

this single line of code gives you the array in return if post thumbnail is available.


I hope this article gave you some insight into how to use get the post thumbnail src in wordpress. If you have any questions, feel free to ask them in the comments.

Leave a Reply:

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