On Multisite: Loop to Show First Four Images of Recent Posts Across Network

I had nothing to do this lunch, so I put together a little function for this. The main thing is to get all the sites within the network and their id. For that I’m using a simple SQL-Query via the class wpdb:

$site_ids = $wpdb->get_results( "SELECT blog_id from $wpdb->blogs" );

It will return a list of blog_id. When I have all the sites am running a foreach on the site_ids and switch_to_blog like this:

// Within the foreach 
switch_to_blog( $site_id->blog_id );

Within the current blog I run a simple get_posts that returns the number of attachmets.

Another foreach on the post that I’m getting from get_posts that uses array_push to set the post_date as key and the post_id as value. The post_date is for the post to be unique in the array and later to sort the images on timestamp.

Next thing is to loop through the data that we set up with post_date as key and post_id as value to get the images with the function wp_get_attachment_image(). That will also use array_push to add the timestamp as key and the image as value. We need the timestamp to sort the order on images. (Latest first) using krsort before we echo out the images.

Here is the full code:

function wpse_77816_ms_last_images( $num_of_images, $size ) {
    global $wpdb;

    // Setup array
    $images = array();

    $site_ids = $wpdb->get_results( "SELECT blog_id from $wpdb->blogs" );

    foreach ( $site_ids as $site_id ) {

        // Swtch to blog
        // http://codex.wordpress.org/WPMU_Functions/switch_to_blog
        switch_to_blog( $site_id->blog_id );

            $posts = get_posts( array(
                'numberposts' => $num_of_images,
                'post_type'   => 'attachment',
                'post_mime_type' => 'image'
            ));

            // Setup array
            $data = array();

            foreach( $posts as $post ) {
                // return array with post_id and post_dates
                $data[strtotime( $post->post_date )] = $post->ID; 
            }

            // Get the images
            foreach( $data as $d => $id ) {
                $images[$d] = wp_get_attachment_image( $id, $size );
            }

        // Restor switch_to_blog
        restore_current_blog();
    }

    // Sort on high to low (time)
    krsort( $images );
    foreach( $images as $image ) {
        echo $image;
    }
}

And you just call it by:

<?php wpse_77816_ms_last_images( 4, 'gallery-overview-thumb' ); ?>

Here you can change 4 to how many images you want per site and whitch size of the images you want.

Leave a Comment