Oshrib
Oshrib

Reputation: 1900

Wordpress meta_query datetime operations

I want to load posts (product type) of all the products that have custom-field ('date_flag'), if the time that stored on this custom field is before more than 4 hours (if 4 hours passed from the date that stored on this custom field).

For example, if 'date_flag' is 2020-11-12 10:00:00 and now its 2020-11-12 14:30:00 then give me this post.

$args= array(
  'post_type' => 'product',
  'posts_per_page' => 5,
  'meta_query' => array( 
    array(
    'key' => 'date_flag',
    'value' => what-to-do-here
    'compare' => what-to-do-here
   ), 

Upvotes: 0

Views: 649

Answers (1)

mikerojas
mikerojas

Reputation: 2338

I suggested reading up more here: https://developer.wordpress.org/reference/classes/wp_meta_query/

// compare against now
array(
  'key' => 'date_flag', // field to check
  'value' => date("Y-m-d"), // today's date 
  'compare' => '<=', // your compare operator
  'type' => 'DATE' // tell WP we're working with date
  )
)

// compare against now + 4 hours
array(
  'key' => 'date_flag', // field to check
  'value' => date("Y-m-d H:i:s", strtotime('+4 hours')), 
  'compare' => '<=', // your compare operator
  'type' => 'DATE' // tell WP we're working with date
  )
)

// compare against some other date + 4 hours
$other_date = '2020-11-12 00:00:00';
$compare_date = date("Y-m-d H:i:s", strtotime('+4 hours', strtotime($other_date));
array(
  'key' => 'date_flag', // field to check
  'value' => $compare_date, 
  'compare' => '<=', // your compare operator
  'type' => 'DATE' // tell WP we're working with date
  )
)

Upvotes: 1

Related Questions