WordPress功能switch_to_blog()
需要一个整数作为输入参数。您可以在法典中了解更多信息:
http://codex.wordpress.org/Function_Reference/switch_to_blog
请尝试这种结构:
// Get the current blog id
$original_blog_id = get_current_blog_id();
// All the blog_id\'s to loop through
$bids = array( 1, 2 );
foreach( $bids as $bid )
{
// Switch to the blog with the blog_id $bid
switch_to_blog( $bid );
// ... your code for each blog ...
}
// Switch back to the current blog
switch_to_blog( $original_blog_id );
更新:如果要从每个博客的不同类别获取帖子,可以使用以下示例:
// Get current blog
$original_blog_id = get_current_blog_id();
// Setup a category slug for each blog id, you want to loop through - EDIT
$catslug_per_blog_id = array(
1 => \'video\',
4 => \'news\'
);
foreach( $catslug_per_blog_id as $bid => $catslug )
{
// Switch to the blog with the blog id $bid
switch_to_blog( $bid );
// ... your code for each blog ...
$myposts = get_posts(
array(
\'category_name\' => $catslug,
\'posts_per_page\' => 10,
)
);
// ... etc
}
// Switch back to the current blog
switch_to_blog( $original_blog_id );
示例:下面是一个允许您使用模板标记的示例(这适用于我的多站点安装):
// Get current blog
$original_blog_id = get_current_blog_id();
// Setup a category for each blog id you want to loop through - EDIT
$catslug_per_blog_id = array(
1 => \'video\',
4 => \'news\'
);
foreach( $catslug_per_blog_id as $bid => $catslug )
{
//Switch to the blog with the blog id $bid
switch_to_blog( $bid );
// Get posts for each blog
$myposts = get_posts(
array(
\'category_name\' => $catslug,
\'posts_per_page\' => 2,
)
);
// Skip a blog if no posts are found
if( empty( $myposts ) )
continue;
// Loop for each blog
$li = \'\';
global $post;
foreach( $myposts as $post )
{
setup_postdata( $post );
$li .= the_title(
$before = sprintf( \'<li><a href="%s">\', esc_url( get_permalink() ) ),
$after = \'</a></li>\',
$echo = false
);
}
// Print for each blog
printf(
\'<h2>%s (%s)</h2><ul>%s</ul>\',
esc_html( get_bloginfo( \'name\' ) ),
esc_html( $catslug ),
$li
);
}
// Switch back to the current blog
switch_to_blog( $original_blog_id );
wp_reset_postdata();
下面是上面示例的演示屏幕截图,站点1名为贝多芬,站点4名为巴赫:
PS:感谢@brasofilo提供
link 这澄清了我对
restore_current_blog()
;-)
PPS:感谢@ChristineCooper分享以下评论:
只是一个友好的警告。确保不要将原始博客id设置为变量$blog_id
-- 这是因为在switch_to_blog()
过程$blog_id
将被核心函数覆盖,这意味着当您尝试切换回原始博客时,最终将切换到循环通过的最后一个博客。有点让人困惑。:)