• Hi
    I am trying to replace the ‘medium’ image size with the ‘thumbnail’ image size for Media Library Grid View in order to make it load faster. I managed to find the below snippet from a thread on 2014. I am not sure if it is outdated therefore it does not work. Would you mind to point me to the right direction? Thanks

    add_filter( 'wp_prepare_attachment_for_js', function( $response, $attachment, $meta ) {
    
    $use_size = 'thumbnail'; // Edit this to your needs.
    
    if( 'image' === $response['type'] && ! isset( $response['sizes']['medium'] ) ) {
    
    if( isset( $response['sizes'][$use_size] ) ) {
    $response['sizes']['medium'] = $response['sizes'][$use_size];
    } else {
    $response['sizes']['medium'] = wp_get_attachment_image_src( $response['id'], $use_size );
    }
    
    }
    
    return $response;
    }, 10, 3 );
Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    This part of the first conditional doesn’t make sense to me:
    && ! isset( $response['sizes']['medium']
    The code works when it’s removed. I don’t see how it matters if the element is set or not since we’re always assigning values to it anyway. As medium is a default size, I think it should always be set?

    The part that handles when $response[‘sizes’][$use_size] is not set needs restructuring. wp_get_attachment_image_src() does not return an array with the proper structure compatible with what $response[‘sizes’][‘medium’] is supposed to be. As long as $response[‘sizes’][$use_size] is set, this part of the code is not used, so for your use case you can likely ignore the fact that it’s wrong.

    Thread Starter theblueli

    (@theblueli)

    Hi, this is because I changed the medium size to 960px width, did not aware the media library is pulling the ‘medium’ size which I thought it is pulling ‘thumbnail’ sizes. Therefore I was looking for a way to improve the speed.
    Eventually, I hired someone to correct it for those who may want to know the solution.

    Thanks bcworkz for the hints as well

    add_filter( 'wp_prepare_attachment_for_js', 'custom_wp_prepare_attachment_for_js', 10, 3 );
    function custom_wp_prepare_attachment_for_js( $response, $attachment, $meta ) {
    $use_size = 'thumbnail'; // Edit this to your needs.
    if( 'image' === $response['type'] ) {
    if( isset( $response['sizes'][$use_size] ) ) {
    //echo $response['sizes'];
    $response['sizes']['medium']['url'] = $response['sizes']['thumbnail']['url'];
    } else {
    $response['sizes']['medium'] = wp_get_attachment_image_src( $response['id'], $use_size );
    }
    }
    return $response;
    };

    Hooks: admin_init
    Priority: 999

    • This reply was modified 4 years, 5 months ago by theblueli.
Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘replace the “medium” image size for media library’ is closed to new replies.