Get post from multiple blogs

WordPress のマルチブログから記事を持ってくる関数を作成。

こちらを参考にさせて頂きました。ありがとうございます。
http://blog.cgfm.jp/garyu/archives/2223

$showpostsで表示数を設定可能。


function get_posts_from_all($showposts, $denyBlogs = array()) {

     global $wpdb;

     // current blog id
     $mysiteid = $GLOBALS['blog_id'];

     // get child blog ids
     $blogList = $wpdb->get_results(" SELECT blog_id FROM $wpdb->blogs ORDER BY blog_id" );

     // post count
     $pcount = 0;

     $should_get_amount = $showposts * count($blogList);

     foreach ($blogList as $blog) {

          $blog_id = $blog->blog_id;

          if (in_array($blog_id, $denyBlogs))
            continue; // skip denied
             
          // change to target blog
          switch_to_blog($blog->blog_id);

          // get blog site and url
          $siteurl = get_site_url();
          $blog_name = get_option('blogname');

          // amount of post should get
          $should_get_amount = $should_get_amount - $pcount;
          $my_posts = get_posts("showposts=$should_get_amount&post_status=publish");
          if (have_posts()) {

                // insert values. Use timestams as the key.
               foreach ($my_posts as $post) {
                  if($pcount < $showposts):
                       $pcount++;
                       setup_postdata($post);
              
                       $get_post_time = $post->post_date;
                       $unix_time = strtotime($get_post_time) . ':' . $blog_id . '-' . $post->ID;
                       $entryAry[$unix_time]['quid'] = $post->guid;
                       $entryAry[$unix_time]['ID'] = $post->ID;
                       $entryAry[$unix_time]['title'] = $post->post_title;
                       $entryAry[$unix_time]['date'] = date('Y/m/d', strtotime($post->post_date));
                       $entryAry[$unix_time]['siteurl'] = $siteurl;
                       $entryAry[$unix_time]['blogname'] = $blog_name;
                       $entryAry[$unix_time]['blog_id'] = $blog_id;
              
                       $entryAry[$unix_time]['categories'] = get_the_category($post->ID);
                       $categories_link = '';
                       $categories = get_categories();
                       foreach ($categories as $category) {
                         $categories_link .= '
                         
  • ' . $category->cat_name . '
  • '; } $entryAry[$unix_time]['categories']['link'] = $categories_link; endif; } } } // reset blog restore_current_blog(); // chenge to current blog switch_to_blog($mysiteid); if (count($entryAry) > 0) { krsort($entryAry); // to sort as modified. return $entryAry; } else { return false; } }