Question

I've got to be missing something very basic here. I want to display posts from one site on another. No custom queries (yet), just the plain old posts.

if ( get_current_blog_id() == 1 ) :
    // do regular main site stuff;
elseif ( get_current_blog_id() == 6 ) :
    switch_to_blog( 1 );
    // pull in posts from main blog
    if ( have_posts() ) :
        while ( have_posts() ) :
            the_post();
            get_template_part( 'content/post' );
        endwhile;
    endif;
    restore_current_blog();
else :
    // nothing special
endif;

When I try this, I get the post data from the site I'm trying to pull into (site 6) rather than site 1. I can echo get_current_blog_id() while in the loop, and it tells me I'm in site 1, but the post content ends up coming from from site 6.

Was it helpful?

Solution

You are looping through the posts queried before your switch_to_blog() statement. Your code appears to be from a page template which is executed AFTER the main query has run.

To be clear, the main query is run before the template code is executed. Switching to another site after that does not update the query, therefore your loop is iterating through the original blog (#6).

Try something like this instead:

  switch_to_blog( 1 );
  // pull in posts from main blog
  $query = new WP_Query();

  if ( $query->have_posts() ) {
      while ( $query->have_posts() ) :
        $query->the_post();
        get_template_part( 'content/post' );
      endwhile;
   wp_reset_postdata();
  } else {
  // none were found
  }

  restore_current_blog();

EDIT: updated to use OP's original loop and template part. EDIT 2: clarified order of execution in the first few sentences.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top