wp_get_attachment_image_src and server path

WordPress doesn’t store path of generated sizes anywhere, you need to build it.

As suggested by @kraftner in comments, wp_get_attachment_metadata() can be used to obtain some of the pieces you need to build the path. An alternative is image_get_intermediate_size().

The missing piece is the absolute path of upload folder. In theory, that can be retrieved via wp_upload_dir() but there’s a problem: that function returns the upload folder in the moment it is called, but there’s always the possibility that when the file was uploaded the upload path was different.

So the only possibility is to make the assumption that scaled image is in the same folder of original image.

This assumption may appear hackish, and probably is, but it is used in WordPress core itself by functions like image_downsize() that does exactly string-replacing (see line #184 of media.php), so if you’re looking for the official way.. that’s the one.

Putting things togheter:

function scaled_image_path($attachment_id, $size="thumbnail") {
    $file = get_attached_file($attachment_id, true);
    if (empty($size) || $size === 'full') {
        // for the original size get_attached_file is fine
        return realpath($file);
    }
    if (! wp_attachment_is_image($attachment_id) ) {
        return false; // the id is not referring to a media
    }
    $info = image_get_intermediate_size($attachment_id, $size);
    if (!is_array($info) || ! isset($info['file'])) {
        return false; // probably a bad size argument
    }

    return realpath(str_replace(wp_basename($file), $info['file'], $file));
}

Function above takes the attachment id and a size and returns the path.

I’ve applied realpath before to return paths because that function returns false for non-existent files, so the whole function always returns false if something went wrong.

The only alternative to this flow would be saving by yourself the path of scaled image(s) somewhere, probably post meta, and retrieve when needed, but that can only work for files uploaded after your plugin has been activated…

Leave a Comment