Sort posts from multiple sites by date

You could just usort the array before iterating.

$allBlogPosts = get_posts( array(
  'posts_per_page'   => -1,
  'orderby'          => 'date',
    'order'            => 'DESC'
));

usort($allBlogPosts, 'sortPosts');    

function sortPosts($a, $b){
    return strtotime($a->post_date) - strtotime($b->post_date);
}

//Your display loop...

FYI, if you’re using PHP>=5.3, you can use a closure, which I personally think is cleaner for this type of thing.

Edit: The reason the above isn’t working is because I misread your code and didn’t realize that the $allBlogPosts array never has more than 1 blogs worth of posts in it at a time. This should work:

$allPosts = [];
foreach( $sites as $site ){
  switch_to_blog( $site['blog_id'] );

    $allBlogPosts = get_posts( array(
      'posts_per_page'   => -1,
      'orderby'          => 'date',
        'order'            => 'DESC'
    ));

    foreach( $allBlogPosts as $post ){
      ob_start();
      setup_postdata( $post ); ?>
      <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
        <header class="post__header">
          <?php the_post_thumbnail(); ?>
          <?php if(!is_single()) { ?>
            <time class="timeStamp"><span class="timeStamp__month"><?php the_time("d"); ?> </span> <span class="timeStamp__day"> <?php the_time("F"); ?> </span> </time>
          <?php } ?>
          <?php
            if ( is_single() ) {
              the_title( '<h1 class="post__title">', '</h1>' );
            } else {
              the_title( '<h2 class="post__title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
            }

          if ( 'post' === get_post_type() && is_single() ) : ?>
          <div class="post__meta">
            <?php themway_posted_on(); ?>
          </div><!-- .post__meta -->
          <?php
          endif; ?>
        </header><!-- .post__header -->
        <div class="post__content">
          <?php
            the_content( sprintf(
              /* translators: %s: Name of current post. */
              wp_kses( __( 'Continue reading %s <span class="meta-nav">&rarr;</span>', 'themway' ), array( 'span' => array( 'class' => array() ) ) ),
              the_title( '<span class="screen-reader-text">"', '"</span>', false )
            ) );

            wp_link_pages( array(
              'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'themway' ),
              'after'  => '</div>',
            ) );
          ?>
        </div><!-- .post__content -->
      </article><!-- post -->
      <?php
      $allPosts[] = ['display'=>ob_get_clean(), 'post_date'=>get_the_time('U')];
      wp_reset_postdata();
    }// end foreach for $skiPost as $post

    restore_current_blog();
  }// end foreach for $sites as $site        

  function sortPosts($a, $b){
    return $a['post_date'] - $b['post_date'];
  }
  usort($allPosts, 'sortPosts'); 
  foreach($allPosts as $p) echo $p['display'];

Leave a Comment