Support

Account

Home Forums General Issues Compare date field with current time in query

Solving

Compare date field with current time in query

  • I have a true/false field to determine if uploaded documents should show up in the frontend, and a date field where you can set a specific time when the document should stop showing up in the frontend of the site.

    the date field is in the format of Y-m-d H:i:s

    Having some trouble with structuring my query.

    This is where i left it at earlier today, not working as intended.

    <?php
    
    $now = date('Y-m-d H:i:s');
    $removal_date = get_field('unpublish-time');
    
    $all_publications = new WP_Query(
        array(
                'post_type'         => 'attachment',
                'meta_query'        => array(
                    array(
                        'key'       => $now,
                        'value'     => $removal_date,
                        'compare'   => '>'
                    ),
                    'relation'      => 'AND',
                    array(
                        'key'       => 'show_document',
                        'compare'   => '=',
                        'value'     => 'Yes'
                    )
                )
            )
        );
     
    ?>
    
    <?php if( $all_publications->have_posts() ) { ?>
        
        <ul>
            <?php while ( $all_publications->have_posts() ) { ?>
                <?php $all_publications->the_post(); ?>
                
                <li>Filtered document</li>
        
            <?php } ?>
    
        </ul>
    
    <?php } ?>

    Any help sorting this out and som explanation to where my thought process went wrong is much appreciated!

  • Is it a date field or a date/time field

    ACF stores date fields in “Ymd” format in the DB so you need to use this format in your query.

  • It is a date/time field Set to return/show in this format:

    2021-01-23 12:01:54 | Y-m-d H:i:s

    So my thinking goes, i need to first establish if an unpublished date have been set, and if it has compare it to the current time.

    This is where im at right now: still not working as intended:

       $unpublish      = get_field('unpublish');
        $current_time   = date( 'Y-m-d H:i:s' );
    
        if( ! empty($unpublish) ) {
            array_push( $metaQuery, array(
    
                'key'       => 'unpublish',
                'compare'   => '>',
                'value'     => $current_time,
                ),
            );
        }
    
  • A true/false field saves a “1” for true and “0” for false.

    
    qrray(
                        'key'       => 'show_document',
                        'compare'   => '=',
                        'value'     => '1'
                    )
    
Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.