简体   繁体   中英

Filter Custom Post Type Based on ACF date field value

I have a custom post type called "Events". All these events pages have a ACF Date Field to enter Event start Date . In the events archive page I want to divide these events between two group.

  1. Coming Soon Events - Check event date against current date.
  2. Completed Events - Past Events.

So Coming Soon Events will be like this:

<?php
    $today = date('Ymd');
    $args = array(
        'post_type'     => 'events',
        'nopaging'      => true,
        'orderby'       => 'meta_value_num',
        'meta_key'      => 'event_start_date', //ACF date field
    );
    $upcoming_events = new WP_Query( $args );
    if ( $upcoming_events->have_posts() ) :
?>
<h2>Upcoming Events</h2>
<ul>

<?php while ( $upcoming_events->have_posts() ) : $upcoming_events->the_post(); ?>

<li>
    Title: <?php the_title(); ?><br>
    Date: <?php echo get_field('event_start_date'); ?>
</li>

<?php endwhile; wp_reset_postdata(); ?>

</ul>
<?php endif; ?>

I know there is meta_query to do this.

'meta_query'     => array( array(
    'key'        => 'event_start_date',
    'value'      => '',
    'compare'    => '',
)),

But I'm not sure is how to compare event date against current date. Any help would be appreciated.

With the help of @Wilco I managed to solve the issue. So I'm posting the answer here incase anyone else face the same issue.

<?php
    $today = date('Ymd');
    $args = array(
        'post_type'     => 'events',
        'nopaging'      => true,
        'orderby'       => 'meta_value_num',
        'meta_key'      => 'event_start_date', //ACF date field
        'meta_query'    => array( array(
            'key' => 'event_start_date', 
            'value' => $today, 
            'compare' => '>=', 
            'type' => 'DATE'
        ))
    );
    $upcoming_events = new WP_Query( $args );
    if ( $upcoming_events->have_posts() ) :
?>
<h2>Upcoming Events</h2>
<ul>

<?php while ( $upcoming_events->have_posts() ) : $upcoming_events->the_post(); ?>

<li>
    Title: <?php the_title(); ?><br>
    Date: <?php echo get_field('event_start_date'); ?>
</li>

<?php endwhile; wp_reset_postdata(); ?>

</ul>
<?php endif; ?>

Answer here - https://wordpress.stackexchange.com/questions/11173/what-is-the-correct-way-to-compare-dates-in-a-wp-query-posts-meta-query have much more details regarding meta_query .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM