Using Wordpress and ACF to create a live program

Viewed 24

I'm trying to create a live program within a website, which should display the active/current item of the program. My setup is as follows:

I have create a Custom Post Type called: Events. The post type contains an Advanced Custom Fields fieldset containing two DateTime Picker fields: start_event_date and end_event_date. The format of both fields is d/m/Y H:i.

Now I want to create a query which loops through the Events post type, listing all posts where $now lies within start_event_date and end_event_date (which will only be the active item of the program). My timezone is defined using date_default_timezone_set("Europe/Amsterdam"); and I have a variable for the current time $now, also in d/m/Y H:i.

<?php

    $args = array(  
        'post_type' => 'events',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'order' => 'ASC', 
    );

    $loop = new WP_Query( $args ); 
                
?>

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php
    date_default_timezone_set("Europe/Amsterdam");
    $time = date('d/m/Y H:i');
    $start_date = get_field('event_start_date');
    $end_date = get_field('event_end_date');
                    
    if ( $time >= $start_date && $time <= $end_date ) { ?>
        <li><?php echo get_the_title(); ?></li>
    <?php } 

?>
<?php endwhile; ?>

Unfortunately, this does not work and I actually have no clue how to implement the condition to only list the items where $now is within $start_date and $end_date.

Any ideas would be appreciated. Thanks in advance.

1 Answers

You could try querying the date in a different format. According to the documentation, the Date/Time Picker in ACF stores the date in a certain format in the database. The values you choose when creating the field are simply for display/return values, not how they're actually queried, I believe.

You could try:

<?php

    $args = array(  
        'post_type' => 'events',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'order' => 'ASC', 
    );

    $loop = new WP_Query( $args ); 
                
?>

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php
    date_default_timezone_set("Europe/Amsterdam");
    $time = date('Y-m-d H:i'); // Change the format here to match ACF database format
    $start_date = get_field('event_start_date');
    $end_date = get_field('event_end_date');
                    
    if ( $time >= $start_date && $time <= $end_date ) { ?>
        <li><?php echo get_the_title(); ?></li>
    <?php } 

?>
<?php endwhile; ?>

If this doesn't work, I'd maybe use the above suggestion and use a meta_query in the original query vs. getting the field for each iteration. Documentation gives a good example of that as well.

Related