You may have already figured this one out, but here’s two examples how to do this. In both of my examples I do the sorting first and rendering second. This keeps things cleaner and clearer in my opinion.
Example 1
Loop queried posts and sort them into two helper arrays. If those arrays have posts, loop them through and render posts.
$posts = helper_function_to_query_posts();
$future_posts = array();
$past_posts = array();
$today = strtotime('today');
foreach ($posts as $post) {
if ( $post->post_date >= $today ) {
$future_posts[] = $post;
} else {
$past_posts[] = $post;
}
}
if ( $future_posts ) {
esc_html_e( 'Upcoming Posts', 'sage' );
helper_function_to_handle_looping_and_rendering_of_posts( $future_posts );
}
if ( $past_posts ) {
esc_html_e( 'Past Posts', 'sage' );
helper_function_to_handle_looping_and_rendering_of_posts( $past_posts );
}
Example 2
Loop queried posts and push post html into helper variables. Echo those variables afterwards.
$posts = helper_function_to_query_posts();
$future_posts_html="";
$past_posts_html="";
$post_html_template="<div class="my-post">
<h2>%s</h2>
%s
</div>";
$today = strtotime('today');
foreach ($posts as $post) {
if ( $post->post_date >= $today ) {
$future_posts_html .= sprintf(
$post_html_template,
esc_html($post->post_title),
esc_html($post->post_excerpt),
);
} else {
$past_posts[] = .= sprintf(
$post_html_template,
esc_html($post->post_title),
esc_html($post->post_excerpt),
);
}
}
if ( $future_posts_html ) {
esc_html_e( 'Upcoming Posts', 'sage' );
echo $future_posts_html;
}
if ( $past_posts_html ) {
esc_html_e( 'Past Posts', 'sage' );
echo $past_posts_html;
}