Why not use get_comments()
, instead of trying to roll your own with $wpdb
?
function display_sitewide_comments() {
$sites = wp_get_sites();
$network_comments = array();
$max = 20;
foreach( $sites as $site ) {
switch_to_blog( $site->blog_id );
$args = array(
'number' => $max,
'status' => 'approved',
);
$network_comments[$site->blog_id] = get_comments( $args );
restore_current_blog();
}
// inspect the comments
var_dump( $network_comments );
}
Edited to add:
If you just want the 20 most recent comments, you could change $network_comments[$site->blog_id] = get_comments( $args );
to something like
$comments = get_comments( $args );
foreach( $comments as $comments ) {
$network_comments[] = $comment;
}
Then, at the end of the loop, use usort()
to sort the comments based on $comment->comment_date_gmt
and then truncate it to $max
values.