I’m trying to pull multiple sites posts. For example, I can pull out a single site
posts by a category and total posts 10.
But I’m trying to pull out both posts from two separate Multisite blogs 1 & 2. But only blog 1 works. Also, I want to pull out another category from blog 1 and blog 2 by another category. How can I achieve this?
Here’s what I am trying to do:
<?php
global $switched;
switch_to_blog(1,2); //switched to 1 & 2 but only 1 working
// Get latest Post
$latest_posts = get_posts('&cat=64&showposts=10');
$cnt =0;?>
<ul>
<?php foreach($latest_posts as $post) : setup_postdata($post);?>
<li>
<a href="<?php echo get_page_link($post->ID); ?>" title="<?php echo $post->post_title; ?>"><?php echo short_title('...', 7); ?></a>
</li>
<?php endforeach ; ?>
<?php restore_current_blog(); //switched back to main site ?>
The WordPress function
switch_to_blog()
expects an integer as an input parameter. You can read more about it in the Codex:http://codex.wordpress.org/Function_Reference/switch_to_blog
Please try this kind of structure instead:
Update:
If you want to fetch posts from different categories for each blog, you can use for example:
Example:
Here is an example that allows you to use template tags (this works on my multisite install):
Here’s a demo screenshot for our above example with site 1 named Beethoven and site 4 named Bach:
PS: Thanks to @brasofilo providing the link that clarifies my misunderstanding of the
restore_current_blog()
😉PPS: Thanks to @ChristineCooper for sharing the following comment:
Take a look at the code in my “Multisite Post Reader” plugin https://wordpress.org/plugins/multisite-post-reader/ . It uses the technique in the other answer to loop through the posts. I also have plugins that do the same thing for images.
Since it is an open-source code, you are welcome to wander through the code and use pieces of it for your own use. (Some of the code is modified from open-source code I found.)