X

Retrieve only the src of a post thumbnail in WordPress

This snippet is 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 would normally use wp_get_attachment_image_src() the returned array contains the URL of the attachment image src, width, height etc. If you are doing this over and over in your themes when you just need to place the URL within an <img src="" tag. You can add the following snippet to the functions.php of your wordpress theme.


Code Snippet:


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.


Code Snippet:


<img src=''<php wpsnipp_post_thumbnail_src(get_the_ID()); ?>'' …/>

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!