latest 5 posts using switch_to_blog loop

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();
}

Leave a Comment

error code: 523