Search code examples
phpwordpressadvanced-custom-fields

WordPress ACF - Find next date in repeater that is not past


I need some assistance on how to query posts using an ACF repeater that contains 'DateTime' fields and return all the posts that haven't already passed. Once I get that query, then display ONLY the DateTime for the next upcoming DateTime.

I have this created for a simple non-repeating TimeDate field query that will grab all the posts that have a start_date after today, but I am not sure how to convert it into filtering using the repeater instead:

$date_now = date('Y-m-d H:i:s');
$time_now = strtotime($date_now);

$args = array(
    'post_type' => array('events-schedule'),
    'post_status' => array('publish', 'private'),
    'posts_per_page' => 8,
    'meta_query'     => array(
            array(
                'key'         => 'end_date',
                'compare'     => '>=',
                'value'       => date('Y-m-d H:i:s'),
                'type'        => 'DATETIME'
            )
        ),
    'order'          => 'ASC',
    'orderby'        => 'meta_value',
    'meta_key'       => 'start_date',
    'meta_type'      => 'DATETIME',
);

Example Data: enter image description here

I need to return the next sub_field that is in the future ONLY (Sept 10) in the first table cell below;

$post_query = new WP_Query($args);
if ($post_query->have_posts()) {
    ?> 
    <div class="events_widget">
        <table> <?php
    while ($post_query->have_posts()) {
        $post_query->the_post(); 

        $date = get_field("start_date");
        $month = date("M", strtotime($date));
        $day = date("d", strtotime($date));

        ?> 

        <tr>
            <td width="100px"><span id="month"><?php echo $month;?></span></br><span id="day"><?php echo $day;?></span></td>
            <td><a href="/events-schedule/<?php get_post_permalink( the_id() ); ?>"><?php the_field('location'); ?></a></td>
            <td><a href="/events-schedule/<?php get_post_permalink( the_id() ); ?>"><?php the_field('event_title'); ?></a></td>
            <td width="100px"><?php the_field('cost'); ?></td>
        </tr>
        <?php

    }
    ?> </table> 
    </div><?php
}

Solution

  • alter your query:

    $date_now = current_time( 'mysql' );
    
    $args = array(
        'post_type' => array('events-schedule'),
        'post_status' => array('publish', 'private'),
        'posts_per_page' => 8,
        'meta_key'       => 'start_date',
        'meta_query'     => array(
                array(
                    'key'         => 'start_date',
                    'value'       => $date_now,
                    'compare'     => '>=',
                )
            ),
        'order'          => 'ASC',
        'orderby'        => 'meta_value',
    );