マルチブログで複数のブログを持っている場合に、最新記事を「親ブログ」にも表示したい事があります。
例えば企業サイトで、支社毎に管理ページでニュースを書くと、それぞれ支社サイトの「ニュース一覧」に表示しますが、本社サイトの「ニュース一覧」にも自動的に表示できるようにします。
functions.phpに下記コードを追加する
(※2019.10.24 wordpressのバージョンアップにより、コード改正)
function get_recentposts_from_network( $args = null ) { $defaults = array( 'num' => 10, 'perblog' => 1, 'start' => 0 ); $r = wp_parse_args( $args, $defaults ); // 全ブログのBLOG_IDを取得 //global $wpdb; //$blogs = $wpdb->get_results( $wpdb->prepare( "SELECT blog_id FROM wp_blogs ORDER BY blog_id" ) ); ////global $wpdb; ////$blogs = $wpdb->get_results( 'SELECT blog_id FROM wp_blogs ORDER BY blog_id', OBJECT ); $blogs = $GLOBALS['wpdb']->get_results( 'SELECT blog_id FROM wp_blogs ORDER BY blog_id', OBJECT ); if( is_array( $blogs ) ) { reset( $blogs ); // 各ブログの最新記事を指定件数取得する foreach( $blogs as $blog ) { switch_to_blog( $blog->blog_id ); $posts = get_posts( "numberposts=" . $r['perblog'] ); if( $posts ) { foreach( $posts as $post ) { $recent_posts[] = $post->post_date; $post->blog_id = $blog->blog_id; $post_list[] = $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; } //endif ( is_array( $blogs ) ) if( $recent_posts ) return array_slice( $recent_posts, $r['start'], $r['num'], true ); return array(); }
テーマ内の使い方
親ブログのIndex.phpに記述
<?php $network_posts = get_recentposts_from_network( 'perblog=3' ); if( $network_posts ) : foreach( (array) $network_posts as $key => $post ) { switch_to_blog( $post->blog_id ); setup_postdata( $post ); ?> <li><a href="<?php the_permalink() ;?>"><?php the_title(); ?></a></li> <?php restore_current_blog(); } wp_reset_query(); endif; ?>
パラメーター
num : 表示件数(初期値 = 10)
perblog : 各ブログから取得する記事件数(初期値 = 1)
start : 表示を開始する投稿数(初期値 = 0)
各ブログから新着記事を5件ずつ取得
$network_posts = get_recentposts_from_network( ‘perblog=5′ );
最新の1件を飛ばして20件表示
$network_posts = get_recentposts_from_network( ‘num=20&start=1′ );
イメージアイコンを記事タイトルの前に付ける
どのブログの記事なのか一目瞭然にしたいですよね。
ブログ別のアイコンを表示するコードのメモです。
下記のように記述で表示できました。
アイコン(icon.png)は、ブログ別に作成して、各ブログのテーマディレクトリーのimgディレクトリーに格納
<li><img src="<?php bloginfo('template_url'); ?>/img/icon.png" class="icon" /><a href="<?php the_permalink() ;?>"><?php the_title(); ?></a></li>
適宜、スペースが欲しいので、imgにclass指定して体裁を整えます。