如何在WordPress多站点中从其ID获取帖子内容


How to get post content from its ID in WordPress multi site?

我正在运行一个多站点,我想从两个博客中提取具有某些类别的帖子。因此,我正在为每个博客运行一个循环来拉取帖子,因为其中一个类别在博客 1 中,而另一个类别在博客 2 中。

    <?php $value = array(); ?>
    <?php 
            // Get the values from $_POST
            $original_blog_id = get_current_blog_id(); // get current blog
            $bids = array(1,2); // all the blog_id's to loop through  EDIT
            foreach($bids as $bid):
            switch_to_blog($bid); 

              $args = array(
                'tax_query' => array(
                'relation' => 'AND',
                    array(
                        'taxonomy' => 'Music',
                        'field' => 'slug',
                        'terms' => array('artist', 'club')
                    ),
                        )
                    );
            $the_query = new WP_Query( $args );

    ?>
    <?php $postids = array(); ?>
    <?php if ( $the_query->have_posts() ) { ?>
        <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
            <?php $postids[]=get_the_ID(); ?>
        <?php endwhile; ?>
         <?php $value[] = $postids; ?>
    <?php
        } else {
            // no posts found
            echo 'Nothing found.';
        }  
    ?>
<?php endforeach; ?>
<?php 
    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($value));
    $list = iterator_to_array($it,false);
    $posts = new WP_Query(array( 
        'post__in' => $list,  
        'post_type' => 'post',
        ));

?>
<?php 
    foreach ($posts as $post) {
    setup_postdata($post);  
?>
<?php echo the_title(); ?>
<?php
}

 wp_reset_postdata();     ?>
<?php switch_to_blog($original_blog_id);  ?>

我在数组中获取IDs的原因:

<?php $postids[]=get_the_ID(); ?>

因为我想获取随机帖子。如果此时我得到的不是上述陈述,而是帖子的标题和内容,那么它将按顺序显示。像这样:

BLOG1: POST1,POST2, POST : BLOG2: POST1, POST2, POST3

但是我想要像这样随机顺序的帖子:

BLOG1: POST1, BLOG2: POST3, BLOG1: POST2, BLOG2: POST1: BLOG2: POST2

所以一切正常,即使在foreach循环之外,我也能够获得posts IDs,但问题是:

我无法从这些IDs获取帖子内容。它只给我博客 2 的帖子,因为当前的博客是 2。但它不显示 blog1 中的任何内容,即使postIDlist 数组中也是如此。

谁能帮忙?

解决方案可以是以下,只需将代码添加到您的主题footer.php文件中,尽管这可以放在您的 WordPress 主题中的任何位置,例如:

<?php
  if (!function_exists('display_posts_from_blogs')) {
    function display_posts_from_blogs($blog_id) {
    global $switched;
    switch_to_blog($blog_id); //switched to blog id 2, for example
    // Get latest Post
    $latest_posts = get_posts('category=-3&numberposts=6&orderby=post_name&order=DSC');
    $cnt =0;
?> 

 <ul>
    <?php foreach($latest_posts as $post) : setup_postdata($post);?>
        <li>
            <a href="<?php echo get_page_link($post->ID); ?>" title="<?php echo $post->post_title; ?>"><?php echo $post->post_title; ?></a>
        </li>                                
    <?php endforeach ; ?>
<?php restore_current_blog(); //switched back to main site 
} //end function
}
?>