latest 5 posts using switch_to_blog loop

im sure i must be doing something wrong and would really appreciate a little help.

I am trying to loop through all of my Sub Dir “Multisite” blogs using switch_to_blog, below:

Read More
global $wpdb, $blog_id, $post;
    $blogs = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM wp_blogs ORDER BY blog_id" ) );
    foreach ($blogs as $blog){

        switch_to_blog($blog->blog_id);
        $globalquery = get_posts('numberposts=5&post_type=any');
        restore_current_blog();

    }
    array_merge($globalquery, $portfolio);

It does work (kinda), it moves to the next blog (id = 2) and is retrieving posts, but goes no further and does not retrieve the main blog posts (id = 1).

I am a self proclaimed php noob, but really enjoy learning and i think im doing quite well lol

Please if someone could help me out?

Regards
Rory

UPDATE
I am trying to create a loop that i can pass into an already declared query:

// create query the portfolio (pass it to $wp_query)
        $portfolio_query = new WP_Query( $portfolio );

Related posts

Leave a Reply

2 comments

  1. No, it’s retrieving the posts just fine, but you’re not storing them anywhere. Here’s your code again, with line-by-line documentation:

    // Set up global variables. Great
    global $wpdb, $blog_id, $post;
    
    // Get a list of blogs in your multisite network
    $blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );
    
    // Iterate through your list of blogs
    foreach ($blog_ids  as $id){
    
        // Switch to the next blog in the loop.
        // This will start at $id == 1 because of your ORDER BY statement.
        switch_to_blog($id);
    
        // Get the 5 latest posts for the blog and store them in the $globalquery variable.
        $globalquery = get_posts('numberposts=5&post_type=any');
    
        // Switch back to the main blog
        restore_current_blog();
    }
    
    // Merge the results of $globalquery with a $portfolio array
    array_merge($globalquery, $portfolio);
    

    The trick is that, in every loop of your foreach statement, you’re overwriting the contents of $globalquery. It will only ever have a set of posts from the last blog in your network.

    Instead, set up a container before your foreach and merge your $globalquery results into it:

    $globalcontainer = array();
    foreach ($blog_ids  as $id){
    
        switch_to_blog( $id );
    
        $globalquery = get_posts( 'numberposts=5&post_type=any' );
    
        $globalcontainer = array_merge( $globalcontainer, $globalquery );
    
        restore_current_blog();
    }
    
  2. To get Blog ids you can use:

    $blogs = wp_get_sites ();
    $blogs_id = array();
    foreach ($blogs as $blog) {
        $blogs_id [] = $blog["blog_id"];
    }
    

    instead of:

    global $wpdb, $blog_id, $post;
    $blogs = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM wp_blogs ORDER BY blog_id" ) );