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
}
}
My Answer:
The issue with your code is that the second part of your meta_query is not correctly checking for posts where the last_update field is older than 1 day. The value you are comparing to should be the date and time from 1 day ago, not the current date and time.
Here is the corrected code:
php
$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
}
}
With this code, the query will return posts where the last_update field is empty or where the last update was more than 1 day ago.
Rate this post
4 of 5 based on 4997 votesComments