How to Get Image Thumbnail Filename in WordPress

WordPressI needed to get a post’s image thumbnail filename (only the filename) in WordPress recently and found that it wasn’t as straightforward as I would have thought. WordPress provides a few functions to get a post’s thumbnail such as get_the_post_thumbnail and the_post_thumbnail,  but each of those returned a fully formatted image tag. What I needed was to retrieve the actual filename of the thumbnail for the post.

What you’ll end up doing is grabbing the post’s thumbnail image filename from the database. This is what it looks like:

/*
  * Grab the post's thumbnail filename
*/
global $wpdb;
$the_thumbnail_id = get_post_thumbnail_id($post->ID);
$the_thumbnail_name = $wpdb->get_var( "SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$the_thumbnail_id' AND meta_key = '_wp_attached_file'" );

That’s it. That’s how you can grab the filename of a post’s thumbnail image.

Now, for posterity’s sake, and to remember what an absolutely insane way I originally tried to go about it. I’ll put my original stab at it here:

// extract image src from html image tag
// http://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php
$the_thumbnail = get_the_post_thumbnail($post->ID);
$result = array();
array_push($result,$the_thumbnail);
$img = array();
foreach( $result as $img_tag) {
        preg_match_all('/(alt|title|src)=("[^"]*")/i', $img_tag, $img[$img_tag]);
}
$e = $img[$the_thumbnail];
$the_thumbnail_name = basename($e[0][0]);
$the_thumbnail_name = str_replace('"','',$the_thumbnail_name);

There’s actually a pretty good post on Quora on “What skills do self-taught programmers commonly lack?”, and if there’s no better example of that then my first feeble attempt, then I don’t know what is.

Post written by Ed Reckers

Founder and lead web development consultant at Red Bridge Internet : San Francisco WordPress Developers and Consultants.

3 Responses to “How to Get Image Thumbnail Filename in WordPress”

  1. James

    Thanks for this snip – works great! (I considered the extraction approach, then was about to hit the db when I found this post).

  2. Vinay

    Hey,
    Thanks for the tip, it did save me a fair bit of time, I was trying something similarly insane. Wouldn’t get_post_meta be a better way of doing that thought than querying the database directly?

    $thumbnail_name = get_post_meta($thumbnail_id, ‘_wp_attached_file’);

  3. Barry Kafka

    Useful post, thanks Ed.

    I had to add a Pinterest badge on WordPress blog posts. I ended up using something similar to Vinay’s approach.

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

    Full discussion at http://wordpress.org/support/topic/getting-post-thumbnail-url

Leave a Reply