Get it All
Together

Summary: Toggles all settings to a different blog’s settings, thus allowing you to perform functions as though you were on that blog. Stores the current blog’s settings in a temporary array, so they can be restored when desired.

Detail: This function switches all the settings in the $wpdb object to the new blog ($new_blog), while also updating the current user’s role as per the new blog. The end result is that all operations performed after using the switch_to_blog function will behave as you would anticipate if you were on that new blog. You would presumably use this function along with the restore_blog() function.

This is probably the single most important and strangely, least-used function in the WPMU platform. The advantages of using switch_to_blog are many. For one, it saves you the trouble of having to rewrite the database blog prefix (wp_24_posts, for example), and instead let’s you query the dB using the same pseudonyms you would use in any WordPress setting ($wpdb->posts). For another, you can use all the standard, built in WordPress functions such as get_permalink() exactly as you would in any other setting. Best of all, because it stores all the current blog’s settings in a temporary array, you can quickly restore the settings without a lot of complex coding.

Additionally, since the user’s roles are carried over, and because you’re using the standard WordPress functions, information normally not visible to a user remains invisible without complex coding. For example, if you want to display the most recent posts from a given blog, you can simply switch to that blog, use the get_posts() function to perform whatever tasks you’d like, and switch back. In doing this, you can avoid showing posts from private, spam or adult blogs. Moreover, on each blog, you can eliminate the possibility that visitors could see private or unpublished posts, or that posts set to be visible only to certain user levels. However, users who do have the proper privileges on that second blog will be able to see those additional posts. Thus you can write supple, flexible plugins that play ball with most available plugins on all public blogs. No additional coding is required, nor are lengthy database queries.

A word of warning: do not attempt to use this function to iterate over a variety of blog ID’s hoping to restore the original blog’s ID at the end, unless you switch back to the original blog in between. At first, I thought that this would be possible, but it is not. Thus, swapping back and forth between several blogs would need to be done like this pseudo-code:

switch_to_blog(4)
. . . do some stuff . . .
restore_blog()
switch_to_blog(5)
. . . do some stuff . . .
restore_blog()