The Switch
As part of a WPMU (WordPress Multisite) setup there’s fantastically useful function called switch_to_blog(), which you can use in your theme files. Firstly, you’ll need to find out the ID of the site you want to switch to. You can do this in the WordPress admin area by going to Sites > All Sites, then hover on one of your blogs/sites, you should see the blog ID in the link. For this example we’re going to switch to a site with the ID of 1. Here’s how you can use the function to switch sites:
switch_to_blog(1); //switch to blog/site 1
Next, you’ll need the ID number of a post on site 1 that you want to get some content from. Again, you can find this out in the admin area by hovering over the title of your post under Posts > All Posts. We’ll put this ID (250 for this example) into a variable so we can use it when calling the post’s content. We’ll also get the title and the excerpt too and wrap them with a h1 tag and a p tag respectively:
$post_id = 250; //set the post ID that you want to get echo '<h1>' . the_title() . '</h1>'; //title echo '<p>' . the_excerpt() . '</p>'; //excerpt //get the post content and display it $content_post = get_post($post_id); $content = $content_post->post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo $content;
Lastly, we need to switch back to our original site. There’s a ready made function for that too:
restore_current_blog(); //restore previous blog/site
Here’s all of the code in one snippet:
switch_to_blog(1); //switch to blog/site 1 $post_id = 250; //set the post ID that you want to get echo '<h1>' . the_title() . '</h1>'; //title echo '<p>' . the_excerpt() . '</p>'; //excerpt //get the post content and display it $content_post = get_post($post_id); $content = $content_post->post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo $content; restore_current_blog(); //restore previous blog/site
In what ways have you used the switch? Let us know in the comments below.
More about Multisite
A multisite network is a collection of sites that all share the same WordPress installation. They can also share plugins and themes.
WordPress Codex
- You can learn more about WordPress Multisite on the WordPress Codex
- Here’s an excellent guide by WPMU DEV: The Ultimate Guide to WordPress Multisite
- Here’s a great example, written by a Lead Web Developer, of how a Multisite Network can be used to good effect for a cluster of schools: Developing a Multisite Network of Websites
Comments (2)
Whether you have feedback, a question, want to share your opinion, or simply want to say thank you - we welcome comments! Please read the disclaimer.
Thanks for this. After fixing it works fine. You’ve parsing errors…
echo ” . the_title(); . ”; //title
No ; is required after function