X

Retrieve Only the src of a Post Thumbnail in WordPress

Looking for a great way to simplify adding images to your theme? This snippet will retrieve only the src of a post thumbnail in WordPress when passed the post ID. To retrieve just the image URL, you’d normally use wp_get_attachment_image_src() and the returned array would contain the URL of the attachment image src, width, height etc. If you’re doing this over and over in your themes, you just need to place the URL within an <img src="" tag. Or, you can add the following snippet to the functions.php of your WordPress theme.

function wpsnipp_post_thumbnail_src($post_id, $echo = true) {
    $attachment = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), $size);
    if(!$echo){
      return $attachment['0'];
    }else{
      echo $attachment['0'];
    }
}

Just add the following within the WordPress loop.

&lt;img src="&lt;php wpsnipp_post_thumbnail_src(get_the_ID()); ?&gt;" .../&gt;

Comments  Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!