I'm using WPMU to power a network of sites. They all have their own content, but the main blog - #1 in the database - has a large chunk of content that I'd like to use across the other sites.
Is there a way to write a function to get that content and use a regular loop on my other themes and sites on that WPMU installation without getting into RSS stuff?
For example, I have a category (ID 5) on blog #1, and I'd like to display the latest 5 posts from category #5 on blogs 2, 3, 4, etc. in a regular loop so I can access postdata, attachments, and so on. Can that be done?
Dan Davies answers:
This can be done with the switch_to_blog function, like this:
<h3>Latest on this blog</h3>
<?php $current = new WP_Query('showposts=5'); ?>
<?php if($current->have_posts()) : ?><?php while($current->have_posts()) : $current->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
<h3>Latest on blog 4</h3>
<?php switch_to_blog(4); ?>
<?php $blog4 = new WP_Query('showposts=5&cat=5'); ?>
<?php if($blog4->have_posts()) : ?><?php while($blog4->have_posts()) : $blog4->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
<?php restore_blog(); ?>
restore_blog returns the the global array back to the blog the user is on, rather than the blog defined in switch_to_blog.
Hope that helps!
James Tryon answers:
Out of the box wordpress.mu dose not do this, we where going to write a plugin that dose this.
We would be happy to look into this for you if you would like. but As of now this is not something that is going to work.
What you could do is call RSS from the first blog, and set it up in XML.
Hope this helps, sorry about the bad news.
Max answers:
You could try the function switch_to_blog(n)
[[LINK href="http://codex.wordpress.org/WPMU_Functions/switch_to_blog"]][[/LINK]]
You should be able to use the normal loop to retrieve the posts and than go back to the previous blog using use restore_current_blog()
Ron Rennick answers:
Hey Dan,
Darfuria has the right answer except it's restore_current_blog()
instead of restore_blog()
.
Going beyond the answer to the question you asked, I suggest using get_
functions and cache a copy of the data pulled in the loop & storing it with the _site_options()
and run the cache on something like a 1/2 hour or 1 hour expiry. Switch to blog runs a few queries and uses up quite a bit of execution time.