2011.8.28:別サイトにて修正版をアップしました。
—
WordPress3.0以降で標準で使える様になった、複数のブログをひとつのWordPressで管理できるネットワーク機能。ネットワーク内のブログの新着記事は普通トップページに表示したいと思うので、表題の機能は需要がありそうだからテンプレートタグがあってもいいのになぁと思うのですが、見つからなかったので自作。いや、ほんとに探したらあるのかもしれないけど!
方針
functions.phpに、ネットワーク内の全ブログから最新1件の投稿を取得し、時系列で並び替える関数を用意する。表示はお好みで。
関数(functions.phpに入れるととりあえず使えます)
// $startを1以上にすると最新のn件を飛ばして取得できます
// $numで取得する件数を指定。
function get_recentposts_from_network( $start = 0, $num = 10 ) {
$recent_posts = get_site_option("network_recentposts");
// データが残っていない場合、60秒以上経過している場合はアップデートする
if( is_array( $recent_posts ) ) {
if( ( $recent_posts['time'] + 60 ) < time() ) { // cache for 60 seconds.
$update = true;
}
} else {
$update = true;
}
if( $update == true ) {
unset( $recent_posts );
// 全ブログのIDを取得
$blogs = get_blog_list( 0,'all' );
if( is_array( $blogs ) ) {
reset( $blogs );
// 各ブログの最新1件を取得する
foreach( $blogs as $blog ) {
switch_to_blog( $blog['blog_id'] );
$posts = get_posts( 'numberposts=1' );
if( $posts ) {
foreach( $posts as $post ) {
$recent_posts[$blog['blog_id']] = $post->post_date;
$post_list[$blog['blog_id']] = $post;
} // endforeach
unset( $posts );
} // endif ( $posts )
restore_current_blog();
} // endforeach
// 投稿日時で並べ替える
arsort( $recent_posts );
reset( $recent_posts );
foreach( (array) $recent_posts as $key => $details ) {
$t[$key] = $post_list[$key];
} // endforeach
unset($recent_posts);
$recent_posts = $t;
update_site_option( "network_recentposts", $recent_posts );
} //endif ( is_Array( $blogs ) )
} // endif ( $update == true )
if( $recent_posts )
return array_slice( $recent_posts, $start, $num, true );
return array();
}