Get the Direct Link to a Post’s Featured Image

I used WordPress’ get_the_post_thumbnail() function in order to output the current post’s featured image. It was great, until I had to link to the featured image. To do that, I needed the value of the SRC attribute of that IMG tag, i.e., the direct link to the featured image.

Thanks to phpxref, and the WordPress Codex, I managed to write a small useful function just for that. Without further ado, I present to you, the function:

function oy_get_direct_thumbnail_link( $post_id = NULL ) {
    global $id;
    $post_id = ( NULL === $post_id ) ? $id : $post_id;
    $src = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'full');
    $src = $src[0];
    return $src;
}

The first and only parameter ($post_id) is optional. If used inside the loop, it fetches the current post’s ID by itself.

About the author

Oren Yomtov

Hi, I’m Oren. I’m a technologist and entrepreneur.

I started coding at a young age, served in IDF's Technological Unit, worked in Silicon Valley, and co-founded a VC-funded startup acting as CTO.

Interested in consulting? Reach out using the contact page.

1 Comment

Hi, I’m Oren. I’m a technologist and entrepreneur.

I started coding at a young age, served in IDF's Technological Unit, worked in Silicon Valley, and co-founded a VC-funded startup acting as CTO.

Interested in consulting? Reach out using the contact page.

Subscribe via email

Photo stream