Secrets of WPMU

Tagged


Right, time for a new series to make its debut on Sillyness, and look at that its WordPress!


I am not sure how long this series will be, but since I have worked with MU quite a bit over the last 2 years or so, I thought it was high time to share some of the crap I have learned with all of you out there in the intarwebs.


Today I am going to show you how to grab the most recent post from every blog on your network, and list it in your home template. Something that I think would be desirable on any network/community based WPMU install.


Oh and you will find a zip containing this plugin at the end of the article, as well as a raw text file.

First, some basics


First we need to understand how WPMU handles multiple blogs. For each blog created on your server, a new set of tables is created that follows this pattern:

prefix_blogNumber_tablename


Pretty straightforward. If you are the second blog to be added to the server, then your posts table would be:

wp_2_posts


Make sense? Good, lets move on. To get a list of the currently active, public blogs on your server, you need to hit the blogs table.


Here WPMU keep tracks of the status of each blog that is created on your server. Is it adult? Has it been marked as spam? Is it private? All these values are tracked in this table.

Let's get into some code


To get an array of all the public blogs on your server simply call the following:


class NewestPosts
{
function get_newest() {
global $wpdb;
$newest= array();
$active_blogs= $wpdb->get_results("SELECT blog_id, domain, path 
FROM $wpdb->blogs WHERE public= 1");


Now that you have an array of all your active blogs, it is pretty simple to loop through them and grab the newest post from each:


foreach( $active_blogs as $blog ) {
   $post= $wpdb->get_results( "SELECT ID, post_author, post_date,
   post_modified, post_title, post_content FROM $wpdb->base_prefix" 
   . $subsite . "_posts WHERE post_status= 'publish' AND post_type 
   != 'revision' ORDER BY post_date DESC LIMIT 1" );
   $newest[]= $post;
}

usort( $newest, array( $this, 'date_sort' ) ); return $newest; }


You'll notice that we are performing a sort on the contents of the newest array above. The function we are calling "date_sort" looks like this:


function date_sort($a, $b) {
    $a = $a->post_date;
    $b = $b->post_date;
    if ( $a == $b ) {
        return 0;
    } else {
        return ( $a > $b ) ? -1 : 1;
    }
}



When we call this function from our home template, we should have an array returned containing the newest post from each active blog, ordered by publication date.


At this point you can style it in whatever way you wish using WPMU's normal function calls. Pretty easy stuff. As always your mileage may vary, so if you have any questions or problems leave me a comment and I will see what I can do to help out.

Source Code


And here's the promised source:

Platform: WPMU Zip File

Platform: WPMU Raw PHP