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名为Beethoven,站点4名为Bach:
PS:感谢@brasofilo提供的链接阐明了我对restore_current_blog()
;-)的误解
PPS:感谢@ChristineCooper分享了以下评论:
只是一个友好的警告。确保不要将原始博客ID设置为变量$blog_id
-这是因为在此switch_to_blog()
过程中,$blog_id
核心功能将覆盖该博客ID ,这意味着当您尝试切换回原始博客时,最终会切换到最后一个博客一个你循环。有点令人费解。:)