How to get all images and their thumbnails from wp media library

Here’s what you can do.

  1. Get a list of all available thumbnail sizes
  2. Query all the attachments
  3. For each attachment size, get it’s URL and save it into the array

Let’s change your code into this:

function get_images_highcompress_data() {
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image/jpeg,image/jpg,image/png',
        'post_status' => 'inherit',
        'posts_per_page' => -1,
        'orderby' => 'id',
        'order' => 'ASC'
    );
    // Get all the available thumbnail sizes
    $sizes = get_intermediate_image_sizes();
    // Query the attachments
    $query_images = new WP_Query( $args );
    $images = array();
    // Run a loop
    if ( $query_images->have_posts() ){
        while ($query_images->have_posts()){
            $query_images->the_post();
            // For each attachment size, store its URL in an array
            foreach ( $sizes as $key => $size ) {
                $thumbnails[$key] = wp_get_attachment_image_src( get_the_ID(), $size)[0];
            }
            $images = array_merge( $thumbnails , $images );
        }
        return $images;
    }
}

The returned array will look like this:

[0] => thumbnail-url,
[1] => medium-url,
[2] => large-url,

And so on.

Leave a Comment