How do I display all posts from multisite to the main site? Please help me. thanks.
2 Answers
So, actually there is two ways to do it.
The first one is using switch_to_blog()
and restore_current_blog()
functions, example:
// in this variable you can pass all the blog IDs you would like to display posts from
$blog_ids = array( 1, 3 );
foreach( $blog_ids as $id ) {
switch_to_blog( $id );
$args = array(); // any WP_Query args should be here
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() : $query->the_post();
// your post template goes here
endwhile;
endif;
wp_reset_postdata();
restore_current_blog();
}
But if you do not want to switch between the blogs each time, then I recommend my – paid and restricted access – plugin which indexes all the posts from all your website into another database table and then you can use WP_Query analogue to get all the posts within just one loop. Example of this plugin https://rudrastyh.com/plugins/get-posts-from-all-blogs-in-multisite-network
That's exactly what my "Multisite Post Reader" plugin does. Grabs posts from any/all multisites. Has tons of optional parameters. It basically does the loop through the sites, similar to the other answer mentioned in the comments.
You are welcome to try it out, or grab the code for your own use. See it here: https://wordpress.org/plugins/multisite-post-reader/ .
I have similar plugins I use for displaying all images from all sites - I use it to monitor images to ensure the subsites meet my content requirements.