retrieve custom image sizes from media uploader javascript object

thanks to a friend on Twitter, I was able to get this working. Below is the code.

function wpse_110060_image_sizes_js( $response, $attachment, $meta ){

        $size_array = array( 'custom_size_one', 'custom_size_two') ;

        foreach ( $size_array as $size ):

            if ( isset( $meta['sizes'][ $size ] ) ) {
                $attachment_url = wp_get_attachment_url( $attachment->ID );
                $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
                $size_meta = $meta['sizes'][ $size ];

                $response['sizes'][ $size ] = array(
                    'height'        => $size_meta['height'],
                    'width'         => $size_meta['width'],
                    'url'           => $base_url . $size_meta['file'],
                    'orientation'   => $size_meta['height'] > $size_meta['width'] ? 'portrait' : 'landscape',
                );
            }

        endforeach;

        return $response;
}
add_filter ( 'wp_prepare_attachment_for_js',  'wpse_110060_image_sizes_js' , 10, 3  );

note: the array and foreach are only necessary because I have two separate ones I needed to include. if there is only 1 to include, that can be removed.

Leave a Comment