find a random blogid across my multisite network that has at least one post published

An example that displays an admin notice listing a randomized array with all blog IDs, the result of a get_posts( array( 'numberposts' => 1 ) ) and marking the first one which get_posts result is different from zero.

Result

admin notice listing all blogs and number of posts found

After refreshing:
admin notice after refreshing

Code

add_action( 'admin_notices', 'wpse_60401_print_random_blog' );

function wpse_60401_print_random_blog()
{ 
    global $wpdb;

    $rows = $wpdb->get_results( $wpdb->prepare( "SELECT blog_id from $wpdb->blogs WHERE public="1" AND archived = '0' AND mature="0" AND spam = '0' AND deleted = '0';" ) );

    if( !$rows )
    {
        echo '<div class="error">No blogs found (!)</div>';
    }
    else
    {
        shuffle( $rows );
        $counter = 0;
        echo '<div class="error">';
        foreach ( $rows as $row ) 
        {
            switch_to_blog( $row->blog_id );
            $get_posts = get_posts( array( 'numberposts' => -1 ) );
            echo 'Blog ID: ' . $row->blog_id . ' - Number posts: ' . count($get_posts) . '<br />';

            if( count($get_posts) != 0 && $counter == 0 ) 
            {
                echo 'First blog with a post: ' . $row->blog_id . '<br />';
                $counter++;
            }
                    restore_current_blog();
        }
        echo '</div>';
    }

}

Code in form an usable function

function get_random_blog()
{ 
    global $wpdb;

    $rows = $wpdb->get_results( $wpdb->prepare( "SELECT blog_id from $wpdb->blogs WHERE public="1" AND archived = '0' AND mature="0" AND spam = '0' AND deleted = '0';" ) );

    if( !$rows )
    {
        return 0;
    }
    else
    {
        shuffle( $rows );
        foreach ( $rows as $row ) 
        {
            switch_to_blog( $row->blog_id );
            $get_posts = get_posts( array( 'numberposts' => -1 ) );

            if( count($get_posts) != 0 ) 
            {
                restore_current_blog();
                return $row->blog_id;               
            }
        }
    }
    restore_current_blog();
    return 0;
}

Leave a Comment