首页 > 解决方案 > Wordpress meta_query 日期时间操作

问题描述

我想加载具有自定义字段('date_flag')的所有产品的帖子(产品类型),如果存储在此自定义字段上的时间超过 4 小时(如果从存储日期过去 4 小时)此自定义字段)。

例如,如果“date_flag”是 2020-11-12 10:00:00,现在是 2020-11-12 14:30:00,那么给我这个帖子。

$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
   ), 

标签: phpmysqlwordpress

解决方案


我建议在这里阅读更多内容: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
  )
)

推荐阅读