合并多个wp_Query对象

时间:2012-09-11 作者:Ian Hoar

我有下面的多站点安装代码。它工作得很好,但我需要将每个多站点中的每个WP\\u查询循环对象合并在一起,以便在另一个模板中使用WordPress循环。这可能吗。我尝试将对象与以下对象合并:

$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);       
但它不起作用,因为对象包含函数。想法?

<?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 个回复
最合适的回答,由SO网友:chrisguitarguy 整理而成

如果只需要每个WP\\U查询对象的帖子,可以执行以下操作:

<?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
}
看来,在这种情况下,您最好使用get_posts 而不是手动创建WP\\u查询对象。您只需要结果数组,这就是get_posts 当然,它使用WP_Query 在幕后。

<?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();
}
您应该知道get_post_meta 当您最终循环浏览这些帖子时,诸如此类的东西不会像您希望的那样工作——您几乎只需要处理每个帖子对象。

结束