List posts from all blogs in WordPress multisite
This was one annooying thing to do. It is hard to find any information about how to list posts from all blogs in WordPress multisite. Most websites just refer to a plugin that costs at least $19 a month. I did not want to use that plugin. And I want to do it in the template, so that I can customize the output in the most seo-friendly way, so I had to Google around a little, do some trial and error, and this is now one way to do it:
List posts from all blogs in WordPress multisite installation
The code:
<?php
$blogs = get_last_updated();
echo ‘
<h1>Last blog posts in all blogs</h1>
‘;
foreach ($blogs AS $blog) {
echo ”
<h2><a href=’http://”.$blog[“domain”].$blog[“path”].“‘>”.get_blog_option( $blog[ ‘blog_id’ ], ‘blogname’ ).“</a></h2>
“;
switch_to_blog($blog[“blog_id”]);
$lastposts = get_posts(‘numberposts=1’);
foreach($lastposts as $post) :
setup_postdata($post);
?>
<a href=”<?php the_permalink(); ?>“><?php the_title(); ?></a>
<?php
endforeach;
restore_current_blog();
}
?>
This code will do some magic. It will print the blogs title with a link to the blog front page (in the h2), and under it a link to the last blog post in that blog, with the blog post title as the anchor text. This code can be developed a lot more, but this is a start!
Note!
This code for listing posts from all blogs in a WordPress multisite installation only works for a multisite where yuo have blogs as subfolders. If you have them as subdomains, you have to modify the code a little. ($blog[“path”] and $blog[“domain”] need to switch positions in a subdomain installation)
I hope it helped you. It would have helped me if this code were present when I searched for it.