Merging multiple wp_query objects

I have the code below for a multisite install. It works fine, but I need to merge each WP_Query loop object from each multisite together for use in another template with the WordPress loop. Is this possible. I’ve tried merging the objects with:

$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);       

But it doesn’t work since the objects contain functions. Ideas?

<?php

// Set up global variables. Great
global $wpdb, $blog_id, $post, $merged_loop;

// Get a list of blogs in your multisite network
$blogs = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM ftc_blogs ORDER BY blog_id" ) );

// Iterate through your list of blogs
foreach ($blogs as $blog){

    // Switch to the next blog in the loop.
    // This will start at blog_id == 1 because of the ORDER BY statement.
    switch_to_blog($blog->blog_id);

    // Get the 5 latest posts for the blog and store them in the $query variable.
    $args = array( 'post_type' => array('post', 'page'), 'category_name' => 'dashboard', 'posts_per_page' => 5 );
    $loop = new WP_Query( $args );

    // need to merge $loop data into $merged_loop for use in template.

    // Switch back to the main blog
    restore_current_blog();
}

endif;
?>

1 Answer
1

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