Search code examples
phpwordpressadvanced-custom-fieldsacfpro

Wordpress ACF query posts where datetime field is empty or older than 1 day


I have a custom post type (affiliate_products) with a price field that I update daily via an API and a WP Cron job. Because I have so many affiliate products on my website, I divide them into batches of 5, with a cron that runs every minute.

For this, I am using an ACF DateTime field last_update that is updated with the current date and time when it is updated. But I am having trouble with my WP query;

I need to get 5 posts where the last_update field is empty (new products that have not been updated yet) OR where the last update was more than 1 day ago. (date < today)

But my query is not working. The first part of the meta query is working, but as soon as I add the second part of the meta_query, no results are returned anymore, even though there are still plenty of products with an empty last_update field. What could be wrong with my code?

I realize I don't have any products yet with a last_update date of > 1 day, but it should still be returning products with an empty last_update field, right?

$args_products = array(
        'posts_per_page'    => 5,
        'post_type'         => 'affiliate_products',
        'meta_query'        => array(
            'relation'          => 'OR',
                array(
                    'key'       => 'last_update',
                    'compare'   => 'NOT EXISTS'
                ),
                array(
                    'key'       => 'last_update',
                    'value'     => date('Y-m-d H:i:s'),
                    'compare'   => '<',
                    'type'      => 'DATETIME'
                ),
            )
    );

    $the_product_query = new WP_Query( $args_products );

    if( $the_product_query->have_posts() ) {
        while( $the_product_query->have_posts() ) { 
            $the_product_query->the_post();
            // the update code goes here
        }
    }

Solution

  • Try Ymd format. check here date-picker

    $args_products = array(
        'posts_per_page'    => 5,
        'post_type'         => 'affiliate_products',
        'meta_query'        => array(
            'relation'          => 'OR',
                array(
                    'key'       => 'last_update',
                    'compare'   => 'NOT EXISTS'
                ),
                array(
                    'key'       => 'last_update',
                    'value'     => date('Y-m-d H:i:s',strtotime('-1 day')),
                    'compare'   => '<',
                    'type'      => 'DATETIME'
                ),
            )
    );
    
    $the_product_query = new WP_Query( $args_products );
    
    if( $the_product_query->have_posts() ) {
        while( $the_product_query->have_posts() ) { 
            $the_product_query->the_post();
            // the update code goes here
        }
    }