/ Published in: PHP
A function to query the 10 most recent posts on a multisite WordPress installation
Expand |
Embed | Plain Text
function recent_mu_posts( $howMany = 10 ) { global $wpdb; global $table_prefix; // get an array of the table names that our posts will be in // we do this by first getting all of our blog ids and then forming the name of the // table and putting it into an array $rows = $wpdb->get_results( "SELECT blog_id from $wpdb->blogs WHERE public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0';" ); if ( $rows ) : foreach ( $rows as $row ) : $blogPostTableNames[$row->blog_id] = $wpdb->get_blog_prefix( $row->blog_id ) . 'posts'; endforeach; # print_r($blogPostTableNames); # debugging code // now we need to do a query to get all the posts from all our blogs // with limits applied $query = ''; $i = 0; foreach ( $blogPostTableNames as $blogId => $tableName ) : if ( $i > 0 ) : $query.= ' UNION '; endif; $query.= " (SELECT ID, post_date, $blogId as `blog_id` FROM $tableName WHERE post_status = 'publish' AND post_type = 'post')"; $i++; endforeach; $query.= " ORDER BY post_date DESC LIMIT 0,$howMany;"; # echo $query; # debugging code $rows = $wpdb->get_results( $query ); // now we need to get each of our posts into an array and return them if ( $rows ) : foreach ( $rows as $row ) : $posts[] = get_blog_post( $row->blog_id, $row->ID ); endforeach; # echo "<pre>"; print_r($posts); echo "</pre>"; exit; # debugging code return $posts; else: return "Error: No Posts found"; endif; else: return "Error: Could not find blogs in the database"; endif; else: return "Error: Could not find blogs"; endif; }
Comments
Subscribe to comments
You need to login to post a comment.

I am building a site & would like the home page of the main site have latest posts from all sites on it. is there a way to use the array/object created with this function to work with a have_posts() loop? I looped it with php to extract the contents in the right places, which I thought would get me wher I wanted to be, but if the post is a gallery, which uses shortcode, it just displays the shortcode, & I would like to display the gallery.
here is what I used...
well I guess my code didn't go with the comment... it wasn't really important anyways...
ok, modified the code above to not include the post data on return, just blog_id, timestamp, & ID & used this code below to render it like a normal loop...
Hi.. any way to include the blog_id to the $posts object, so I can retrieve thisn info later? greatly appreciated snippl
Sorry for being pretty late, but I found a similar questions that was answered by an accomplished WordPress dev here
The implementation of his solution is a little over my head, but I hope it can lead others in the right direction