I would like to display the first four images from posts across a WordPress network.
In Otto’s image gallery tutorial he recommended using the following to get images from recent posts. Query parameters:
$images = new WP_Query( array(
'post_parent' => get_the_ID(),
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID',
'posts_per_page' => 4,
'post__not_in' => array($thumb_id),
'update_post_term_cache' => false,
) );
Then the following in the loop to display the attachments:
foreach ($images->posts as $image) {
echo '<div class="gallery-image"><a href="'.get_permalink($image->ID).'">'.wp_get_attachment_image( $image->ID, 'gallery-overview-thumb' ).'</a></div>';
I’m trying to do the same in a network.
I started by trying to use the same code along with the “Sitewide Tags Plugin”, but it won’t show the images for sub sites, just images created from the main site dashboard.
Would it be a lot more work to get the same to work across a network?
Thanks so much.
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:
It will return a list of
blog_id
. When I have all the sites am running a foreach on thesite_ids
and switch_to_blog like this: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 fromget_posts
that uses array_push to set thepost_date
as key and thepost_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 andpost_id
as value to get the images with the function wp_get_attachment_image(). That will also usearray_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:
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.