Changing site in WordPress Multisite (e.g. for getting posts from other sites)

I’ve been playing around with WordPress Multisite, and (in some custom plugin code) wanted to be able to get posts from and save posts to a different site to the one that I was in. Thankfully, there are a couple of functions that make this very easy:

switch_to_blog( $id )

restore_current_blog()

What these do is probably fairly self explanatory, but if you give switch_to_blog() the id of a blog, it will switch to that blog. Calling restore_current_blog() with then switch back to the original blog.

For example, to save a post to the current blog, and another blog, you can do the following:

//Post data
$newPost = array(
   'post_title' => 'title',
   'post_content' => 'content',
   'post_status' =>  'publish',
   'post_author' => $userId,
   'post_category' => 'category
);

$postID = wp_insert_post($newPost, false); //Insert post into current blog

switch_to_blog( $otherBlogID ); //Switch to the other blog

$otherPostID = wp_insert_post($newPost, false); //Insert post into other blog

restore_current_blog(); //Switch back to the current blog