This code snippet example uses WP_Query to group event posts by month and adds a pagination that queries the previous and next month’s event results. The custom post type is tribe_events
and the custom field used to arrange is the start date: _EventStartDate
.
<?php
$date = isset( $_GET[ 'date'] ) ? $_GET['date'] : date('Y-m');
$year = date('Y');
$start_date = strtotime(date( $date . '-01' ));
// Get today's date.
$today = date('Y-m-d');
// Find first date of current month.
$start_day = date('Y-m-01', $start_date);
$end_day = date('Y-m-t', strtotime($start_day));
// Find month-year of current query.
$current_month = date('F Y', strtotime($start_day));
// Add one month for "Next Month".
$next_month = date('Y-m', strtotime( "+1 month", strtotime($start_day) ));
// Substract for "Previous Month".
$previous_month = date('Y-m', strtotime( "-1 month", strtotime($start_day) ));
$args = array(
'post_type' => 'tribe_events',
'meta_key' => '_EventStartDate',
'posts_per_page' => 5,
'orderby' => 'meta_value',
'order' => 'ASC',
'date' => intval($date),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_EventStartDate',
'value' => $today,
'compare' => '>=',
),
array(
'value' => array($start_day, $end_day),
'compare' => 'BETWEEN',
'type' => 'DATE',
),
),
);
$events = new WP_Query( $args );
if( $events ): ?>
<section class="latest-events" id="<?php if( !empty($block['anchor']) ) { echo esc_attr( $block['anchor'] ); } ?>">
<div class="wrapper">
<div class="pagination grid">
<div class="prev">
<i class="fas fa-angle-left"></i>
<a href="?date=<?php echo esc_attr( $previous_month ); ?>"><?php esc_html_e( 'Previous Month', 'text-domain' ); ?> </a>
</div>
<div class="current-month"><?php echo esc_html( $current_month ); ?></div>
<div class="next">
<a href="?date=<?php echo esc_attr( $next_month ); ?>"><?php esc_html_e( 'Next Month', 'text-domain' ); ?> </a>
<i class="fas fa-angle-right"></i>
</div>
</div>
<ul class="events-list">
<?php if ( $events->have_posts() ) : ?>
<?php while ( $events->have_posts() ) : $events->the_post();
?>
<li class="events-single">
// Event Info
</li>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
</ul>
</div>
</section>
<?php endif; ?>