WPMU – Get Posts from Other Blog or Site In Current Site Or Blog

WPMU – WordPress Multisite is used to create network of sites on a single WordPress installation. We can create multiple site like http://beta.example.com or http://example.com/beta/ , it depends on which way you want to use it. There are lots of other features available for WPMU which you can read on WordPress WPMU In this post I am going to explain how to get posts from one WPMU site(i.e. http://alpha.example.com ) to other WPMU site (i.e. http://beta.example.com).

WordPress provides many functions which solve lots of issue by using them, So to get posts from other blog to current blog we will use a couple of WPMU functions available. WordPress WPMU provides a function switch_to_blog($blog_id) by which we can switch to any blog. For example if we are accessing page of http://beta.example.com , we can switch to http://alpha.example.com on that page of http://beta.example.com by using switch_to_blog($blog_id), We just have to pass $blog_id of http://alpha.example.com. You can find blog id by going to main site admin (i.e. http://example.com/wp-admin/network/sites.php dont forget to replace http://example.com with your domain name), here you will see all sites you added, Just mouse over on ‘Edit’ link for site which you want to know blog id, you will see in link like this ‘site-info.php?id=2‘ here you can see 2 in red which is blog id.

if ( have_posts() ) :
while ( have_posts() ) : the_post();
//End the loop.

Suppose above code written in a page of http://beta.example.com in which it will show all posts from http://alpha.example.com. Now explaining code line by line. First line switch_to_blog(2); it will switch blog to blog id 2 (i.e. http://alpha.example.com ), So after switching we can use all WordPress functions simply we use, but when we use WordPress functions after switch_to_blog(2); then all functions will be used in context of blog id 2 and will fetch all posts of blog id 2. Line number 2 to 8 will fetch posts and echoed there. Last line restore_current_blog(); after getting posts from http://alpha.example.com we need to restore blog to current blog, if we will not do this then all functions written will use context of blog id 2 instead of current blog. So we use restore_current_blog(); to restore context to current blog.

I hope this post will help you in your projects. Let me know in comments if you have any questions.