Ricks Answer is surely helpful but I wanted to share my approach, which is an adoption or extension of your code:
First get a list of selected blogs in your network.:
$args = array('site__in' => array(2, 3, 6))
$sitesObj = get_sites($args);
$sites = object_to_array($sitesObj);
You can also exclude sites by using 'site__not_in'
in the arguments of get_sites()
.
Convert the $sitesObj
object into an array:
$sites = object_to_array($sitesObj);
object_to_array($object) {
if (!is_object($object) && !is_array($object)) {
return $object;
}
return array_map('object_to_array', (array) $object) ;
}
Then initialize a counter to control the total of posts to show and switch to each selected blog to fire the loop with your custom arguments:
$postCounter = 0;
$maxPosts = 5; // total number of posts to show
foreach ($sites as $site) {
switch_to_blog($site['blog_id']);
$args = array(
'post_type' => 'post', // or custom post type
'posts_per_page' => 2, // number of posts per blog
'order' => 'DESC',
'orderby' => 'date' // you could also use 'rand' here
);
$loop = new WP_Query($args);
if ($loop->have_posts()) :
while ($loop->have_posts() && $counter < $maxPosts) : $loop->the_post();
// your output
endwhile;
endif;
restore_current_blog();
}
I hope that helps :)