Grow your CSS skills. Land your dream job.

Last updated on:

Get Featured Image URL

Post thumbnails are pretty useful and pretty easy to use in WordPress. Simply add:

add_theme_support('post-thumbnails'); 

To a theme's functions.php file and you'll get a Featured Image module on the admin screen for posts which allows you to select one.

It is also very easy to output that image as an HTML <img>:

the_post_thumbnail();

But what if you just need the URL? Say, you're going to use it as a background-image on an element rather than a content image. Unfortunately there is no super easy/obvious function for that.

Within the loop, you'll have to do:

$thumb_id = get_post_thumbnail_id();
$thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
$thumb_url = $thumb_url_array[0];

Then $thumb_url will be that URL.

Comments

  1. Aaron
    Permalink to comment#

    You can also use this code, especially when storing posts in an array:

    $image = wp_get_attachment_url( get_post_thumbnail_id($post->ID));

    • Gerson
      Permalink to comment#

      Saved my butt. Thanks man.

      I am new both WordPress and php so I purchased a theme for my site to simplify things. I have been making changes to the site and was struggling for hours on getting the post attachment url. My problem was that I was looking through the theme functions and files. Oh well. you live and you learn. Thanks again.

    • Aaron, how would you pass the thumbnail size in your code? I tried it, and it shows the url of the original image.

  2. Native Imaging

    Hey Chris, i’m a little stumped on a task with trying to get the featured image source of the next and previous post. i know how to get the featured image of the next and previous posts, im using them for pretty Next/Prev nav buttons, but im also using featured video plus plugin in my theme, so it auto replaces the image with the featured video. excellent plugin, and ive got just the video thumbnail to work on my blog and cat pages by grabbing the img src rather than post_thumbnail, but still stumped on how to do this for Next/Prev navigation on single posts. Any tips you can point out for me?

    Thanx! :)

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".