Merging multiple wp_query objects

If you just need the posts of each WP_Query object, you can do do something like this:

<?php
// fetch blogs here
$all_posts = array()
foreach($blogs as $b)
{
    switch_to_blog($b->blog_id);
    $query = new WP_Query(/* your args here */);
    if($query->have_posts())
        $all_posts = array_merge($all_posts, $query->posts); // posts are stored in the `posts` property
    restore_current_blog(); // FYI: this tends to slow things down
}

It seems, in this case, you might be better off just using get_posts instead of creating a manually creating a WP_Query object. You just want the array of results, which is what get_posts does — of course, it uses WP_Query behind the scenes.

<?php
// fetch blogs here
$all_posts = array()
foreach($blogs as $b)
{
    switch_to_blog($b->blog_id);
    $posts = get_posts(/* your args here */);
    if($posts)
        $all_posts = array_merge($all_posts, $posts);
    restore_current_blog();
}

You should be aware that functions like get_post_meta and the like are not going to work like you want them to when you do finally loop through the posts — you’ll pretty much only have each post object to work with.

Leave a Comment