PHP setting up two output buffers with different contents in while loop

228 views Asked by At

I have a Wordpress site and I am trying to loop over my posts in an AJAX call and I would like to store the HTML for the first post in the loop in a separate variable than the rest of the posts. How would I go about setting up the output buffer

if (have_posts()) :
  $i = 0;while(have_posts()): the_post();
    if ($i == 0):
      ob_start();
      get_template_part('templates/latest-post', get_post_format());
      $recent_post = ob_get_contents();
      ob_end_clean();
    else:
      ob_start();
      get_template_part('templates/remaining-posts', get_post_format());
      $remaining_posts = ob_get_contents();
      ob_end_clean();
    endif;
  $i++; endwhile;
endif;

This isn't working because the ob_start and ob_clean is being called on every iteration so I end up with only 1 post in the $remaining_posts variable, but I'm not sure how to set it up correctly.

1

There are 1 answers

0
Chris Haas On BEST ANSWER

You can just concatenate that content using .=:

// Initialize the remaining posts variable
$remaining_posts = '';

if (have_posts()) :
  $i = 0;while(have_posts()): the_post();
    if ($i == 0):
      ob_start();
      get_template_part('templates/latest-post', get_post_format());
      $recent_post = ob_get_contents();
      ob_end_clean();
    else:
      ob_start();
      get_template_part('templates/remaining-posts', get_post_format());

      // Concatenate
      $remaining_posts .= ob_get_contents();
      ob_end_clean();
    endif;
  $i++; endwhile;
endif;