I 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.