I am trying to put a header before past posts and after future posts.
I'm using get_posts()
in a function to output the posts using a foreach
loop for a custom post type ordered by date (meta key). If a post's associated date is less than the current date (i.e., dates not in the future), I want to output some HTML.
if ($custom_post_date >= $today && $index === 1)
The problem I am running into is that the HTML gets output after the first post that is in the past. How can I output the HTML before the first post that meets the criteria? Is there a way to go back in the foreach
loop or something to that effect?
<?php
$index = 1; // counts all items in query
$count = count($upcoming_posts);
$today = new DateTime();
$past = false;
foreach ($upcoming_posts as $posts) {
if ($post_date >= $today && $index === 1) : ?>
<h2><?php __( 'Upcoming Posts', 'sage' ); ?></h2>
<div class="wp-block-columns has-2-columns">
<?php else ($post_date < $today && $past === false && $index === 1) : ?>
<?php $wp_query->current_post -= 1; ?>
<h2><?php __( 'Past Posts', 'sage' ); ?></h2>
<div class="wp-block-columns">
<?php endif; ?>
<div class="wp-block-column">
<div class="wp-block-media-text alignwide">
...
</div>
</div>
<php if ( ($index % 2) == 0 && $end === false ) : ?>
</div>
<div class="wp-block-columns has-2-columns"> <!-- ends row every other iteration -->
<?php $end = false;
endif;
if ($count == $index ) : ?>
</div> <!-- ends final row -->
<?php endif;
} ?>