Recent Posts from All Sites (WordPress Multisite)


/ Published in: PHP
Save to your folder(s)

A function to query the 10 most recent posts on a multisite WordPress installation


Copy this code and paste it in your HTML
  1. function recent_mu_posts( $howMany = 10 ) {
  2.  
  3. global $wpdb;
  4. global $table_prefix;
  5.  
  6. // get an array of the table names that our posts will be in
  7. // we do this by first getting all of our blog ids and then forming the name of the
  8. // table and putting it into an array
  9. $rows = $wpdb->get_results( "SELECT blog_id from $wpdb->blogs WHERE
  10. public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0';" );
  11.  
  12. if ( $rows ) :
  13.  
  14. $blogPostTableNames = array();
  15. foreach ( $rows as $row ) :
  16.  
  17. $blogPostTableNames[$row->blog_id] = $wpdb->get_blog_prefix( $row->blog_id ) . 'posts';
  18.  
  19. endforeach;
  20. # print_r($blogPostTableNames); # debugging code
  21.  
  22. // now we need to do a query to get all the posts from all our blogs
  23. // with limits applied
  24. if ( count( $blogPostTableNames ) > 0 ) :
  25.  
  26. $query = '';
  27. $i = 0;
  28.  
  29. foreach ( $blogPostTableNames as $blogId => $tableName ) :
  30.  
  31. if ( $i > 0 ) :
  32. $query.= ' UNION ';
  33. endif;
  34.  
  35. $query.= " (SELECT ID, post_date, $blogId as `blog_id` FROM $tableName WHERE post_status = 'publish' AND post_type = 'post')";
  36. $i++;
  37.  
  38. endforeach;
  39.  
  40. $query.= " ORDER BY post_date DESC LIMIT 0,$howMany;";
  41. # echo $query; # debugging code
  42. $rows = $wpdb->get_results( $query );
  43.  
  44. // now we need to get each of our posts into an array and return them
  45. if ( $rows ) :
  46.  
  47. $posts = array();
  48. foreach ( $rows as $row ) :
  49. $posts[] = get_blog_post( $row->blog_id, $row->ID );
  50. endforeach;
  51. # echo "<pre>"; print_r($posts); echo "</pre>"; exit; # debugging code
  52. return $posts;
  53.  
  54. else:
  55.  
  56. return "Error: No Posts found";
  57.  
  58. endif;
  59.  
  60. else:
  61.  
  62. return "Error: Could not find blogs in the database";
  63.  
  64. endif;
  65.  
  66. else:
  67.  
  68. return "Error: Could not find blogs";
  69.  
  70. endif;
  71. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.