2019/01/25
マルチサイト
備忘録です。
現在、マルチブログサイトを制作中ですが、諸々のブログをまとめて表示したいと思い調べてみたところ下記サイトに記述がありました。
参考サイト
マルチサイト内で複数のブログ記事を表示するコード
functions.phpに記述
/* 複数のブログを参照してWP_Post状のデータを作成する関数 */
function get_multisite_posts($a_site_id = array(1), $a_per_post = 10, $a_order_by = 'post_date DESC'){
global $wpdb;
$str = ''; $query;
$sites_id = ($a_site_id == null || $a_site_id == 0 || $a_site_id == '') ? array(1) : $a_site_id ;
$per_post = ($a_per_post == null || $a_per_post == 0 || $a_per_post == '') ? 10 : $a_per_post;
$order_by = ($a_order_by == null || $a_order_by == 0 || $a_order_by == '') ? 'post_date DESC' : $a_order_by;
foreach($sites_id as $site_key => $site_id){
switch_to_blog($site_id);
$str .= "(SELECT *, $site_id AS site_id FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish')";
$str .= ($sites_id[$site_key + 1]) ? ' union ' : ' ';
restore_current_blog();
}
$str .= "ORDER BY $order_by LIMIT $per_post";
$query = $wpdb->get_results($str);
return $query;
}
/* ループ中の記事データをセットする関数 */
function get_multisite_posts_prep($a_entry = false){
$entry = ($a_entry == null || $a_entry == 0 || $a_entry == '') ? false : $a_entry;
if(!$entry){
wp_reset_postdata();
restore_current_blog();
}else{
global $post; $post = $entry;
switch_to_blog($a_entry->site_id);
setup_postdata($post);
}
}
1行目のa_per_post = 10で表示件数を指定します。
記事を表示したいテンプレートに記述
<?php
$entries = get_multisite_posts(array(1, 2)); //ブログIDは配列で指定
foreach($entries as $entry){
get_multisite_posts_prep($entry); //始端では引数はforeachの内部配列に合わせる ?>
<article id="post-<?php echo $entry->site_id; ?>-<?php the_ID(); ?>" class="entry">
<header>
<time><?php the_time('Y-m-d g:i a'); ?></time>
<h1><?php the_title(); ?></h1>
</header>
<section><?php the_content(); ?></section>
<footer>
<p class="categories"><?php the_category(); ?></p>
<p class="tags"><?php the_tags(''); ?></p>
</footer>
</article>
<?php
get_multisite_posts_prep(); //終端では引数なしで現データをリセットする
} ?>
ちなみに他のブログを単一で表示する場合は下記となります。
記事を表示したいテンプレートに記述
<?php
switch_to_blog(10);//ブログのID
$entries = get_posts();
foreach($entries as $entry){
global $post; $post = $entry;
setup_postdata($post) ?>
<article id="post-<?php the_ID(); ?>" class="entry">
<header>
<time><?php the_time('Y-m-d g:i a'); ?></time>
<h1><?php the_title(); ?></h1>
</header>
<section><?php the_content(); ?></section>
<footer>
<p class="categories"><?php the_category(); ?></p>
<p class="tags"><?php the_tags(''); ?></p>
</footer>
</article>
<?php
wp_reset_postdata();
}
restore_current_blog(); ?>
詳しい解説は参考サイトをご覧ください。
2026/11/02
JQuery
css
2026/11/01
車
2026/10/31
神社
御朱印
2026/10/30
AI
Wordpress
AIが書いた原稿をWordPressの「ブロック」に変換して下書きに──Markdownで書かせる理由と、変換で決めた5つのこと
2026/10/29
ホームページ制作
スマートフォン