Image sizes and order of operations

I’m working on optimizing my site, and part of that is compressing images and using smaller versions. I’m using WP Smush and creating a bunch of sizes for each image. All images have been smushed.

My template is pretty custom, and I’m not using the normal WYSIWYG in a few places. In those situations, I wrote two functions to pull smaller image sizes as needed:

(note: the first function is from https://wordpress.org/support/topic/need-to-get-attachment-id-by-image-url)

function get_image_id_by_link($link){
    global $wpdb;

    $link = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $link);

    return $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE BINARY guid='$link'");
}

function get_image_url($url, $preferred_size = 900){
    $id = get_image_id_by_link($url);

    if(wp_get_attachment_image_src($id, array($preferred_size, $preferred_size))) {
        return wp_get_attachment_image_src($id, array($preferred_size,$preferred_size))[0];
    }
    else if(wp_get_attachment_image_src($id, array(900,900))) {

        return wp_get_attachment_image_src($id, array(900,900))[0];
    } 
    else if(wp_get_attachment_image_src($id, 'medium_large')){
        return wp_get_attachment_image_src($id, 'medium_large')[0];
    } 
    else if (wp_get_attachment_image_src($id, 'large')){
        return wp_get_attachment_image_src($id, 'large')[0];
    } 
    else {
        return $url;
    }
}

This function works for any images I upload and use now. But, any images uploaded before I pushed this function always pull the full size image url. I’ve confirmed that those images (the earlier ones) do have smaller sizes.

While I can re-upload all the images, I’m curious why this is happening and how I can fix it.

Thanks!


Edit

Here are the registered sizes, according to get_intermediate_image_sizes():

Array
(
    [0] => thumbnail
    [1] => medium
    [2] => medium_large
    [3] => large
    [4] => medium-box
    [5] => large-box
    [6] => responsive-100
    [7] => responsive-150
    [8] => responsive-200
    [9] => responsive-300
    [10] => responsive-450
    [11] => responsive-600
    [12] => responsive-900
)

1 Answer
1

wp_get_attachment_image_src will always return a URL to a file if the image exists in some size. If the size you ask for doesn’t exist then you get the URL for the full size image as uploaded. (This isn’t the “large” image size.)

So, for a valid image ID, your conditional if(wp_get_attachment_image_src($id, array($preferred_size, $preferred_size))) will always succeed, as wp_get_attachment_image_src always returns a URL, even if that URL isn’t the one you expect.

To fix it, I’d recommend that you don’t subvert the API and that you work with it instead.

Leave a Comment