konweb
1/30/2020 - 6:21 AM

multisite get all post

multisite get all post

<?php
  global $wpdb;
  
  $post_type = 'post'
  $paged = get_query_var('paged') ?: 1;
  $posts_per_page = 5;
  $start = $posts_per_page * ($paged - 1);
  $sql = '';
  $sites = get_sites();
  foreach($sites as $key => $site){
    next($sites);
    switch_to_blog($site->blog_id);
    
    $sql .= $wpdb->prepare("(
      SELECT *, $site->blog_id as blog_id
      FROM $wpdb->posts
      WHERE post_type = %s
      AND post_status = 'publish'
    )", $post_type);
    
    // use meta_query
    /*
    $sql .= $wpdb->prepare("(
      SELECT *, $site->blog_id as blog_id
      FROM $wpdb->posts AS posts
      INNER JOIN $wpdb->postmeta AS pm1 ON (posts.ID = pm1.post_id)
      WHERE
        posts.post_type = %s
        AND posts.post_status = 'publish'
        AND pm1.meta_key = %s
        AND pm1.meta_value = %s
    )", $post_type, 'meta_key', 'meta_value');
    */
    
    // use tax_query
    /*
    $sql .= $wpdb->prepare("(
      SELECT *, $site->blog_id as blog_id
      FROM $wpdb->posts
      INNER JOIN $wpdb->term_relationships as tr ON $wpdb->posts.ID = tr.object_id
      INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
      INNER JOIN $wpdb->terms as t ON t.term_id = tt.term_id
      WHERE post_type = %s
      AND tt.taxonomy = %s
      AND t.slug = %s
      AND post_status = 'publish'
    )", $post_type, 'taxonomy_slug', 'term_slug');
    */
    
    if(current($sites) !== false){
      $sql .= "UNION\n";
    }
    restore_current_blog();
  }
  $total_posts = count($wpdb->get_results( $sql ));
  $sql .= $wpdb->prepare("
    ORDER BY post_date DESC
    LIMIT %d, %d
  ", $start, $posts_per_page);
  $posts = $wpdb->get_results( $sql );

  $the_query = new WP_Query($args);
  $the_query->posts = $posts;
  $the_query->post_count = count($posts);
  $the_query->found_posts = $total_posts;
?>

<?php
  if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
      switch_to_blog( $post->blog_id );
?>
<?php the_title() ?>
<?php
      restore_current_blog();
    endwhile;
  endif;
  wp_reset_postdata();
?>