php: modifying a filename

needed to do this to make wordpress choose the thumbnail image instead of the full-sized image — since some people like to upload gernormous images (recall that wordpress uploads a whole set of images when you upload one)

so this adds a suffix (in this case, “-150×150”) to the of the filename, BUT before the file extension

anyway, here it is:

// set your suffix
$thumbnail_suffix = "-150x150";

// $featured_image is the filename. this would be determined above this code snippet
// determine the length of the filename, including the extension
$length = strlen ($featured_image);

// get the first part of the filename (before the extension)
$temp1 = substr ($featured_image, 0, $length-4);

// get the second part of the filename (the extension)
$temp2 = substr ($featured_image, $length-4, $length);

// stick the suffix in between the two halves
$featured_image_updated = $temp1.$thumbnail_suffix.$temp2;

you might be saying, “but joey.. why don’t you just use something like explode to break up the filename?” well you really don’t know what the filename will be — it could have a bunch of dots in it… if you could figure it out, great. let me know what you did.

at least you know every image file that’ll be uploaded will be a “.” and then three characters after.

Leave a Reply