I have a MU network setup and I'm pulling in media library images and displaying 4 of those images randomly from across the entire network.

I've seen a few people on here using similar codes to do the same thing, my questions is:

How do I crop images pulled directly from the media library dynamically?

Currently the code works however it merely scales the image size and on right click > view image it shows the image in full size and not as a cropped thumbnail etc.

This obviously boosts the page size if each image is 5mb (x4 = 20mb) which is unnecessary, here is the code:

function get_images_from_media_library() {
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' =>'image',
        'post_status' => 'inherit',
        'posts_per_page' => 4,
        'orderby' => 'rand'
    $query_images = new WP_Query( $args );
    $images = array();
    foreach ( $query_images->posts as $image) {
        $images[]= $image->guid;
    return $images;

function display_images_from_media_library() {
    $imgs = get_images_from_media_library();
    $html = '<div id="media-gallery">';
    $html .= '<h3>Oriel / Gallery</h3>';
    foreach($imgs as $img) {
        $html .= '<img src="' . $img . '"/>';
    $html .= '<h4><a href="' . get_site_url() . '/gallery">Weld mwy o / View more <i class="fa fa-chevron-right"></i></a></h4>';
    $html .= '</div>';
    return $html;

Any help or suggestions would be much appreciated.

1 Answer 1


You could try

$images[]= wp_get_attachment_image_src($image->ID, 'thumbnail')

Or define a new image size in functions.php


  • Thanks for the response, I attempted using add_image_size() however it wasn't cropping it, the code pulls the images straight from the image library and not a post or page, I'm assuming that's why it's not able to crop it. I also attempted the first option, just returns the array however I'll play with that more and see if I can get something to come out cropped.
    – whst
    Commented Dec 17, 2013 at 14:14
  • Have you tried thumbnail? I don't use multisite much; the size could be being defined in the wrong place if mutisite uses themes differently. Also, have you flushed your image sizes? when you add a new size you'll need to regenerate all images on the site, this plugin is useful for that: wordpress.org/plugins/force-regenerate-thumbnails
    – Gaffen
    Commented Dec 17, 2013 at 14:17
  • Yeah I'm purging and regenerating the thumbnails as I go but there doesn't seem to be a way to do this using the standard thumbnails and image_sizes. <?php echo display_images_from_media_library(); ?> That's currently how I'm calling the code I posted above
    – whst
    Commented Dec 17, 2013 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.