【问题标题】:How can I order a wp_query with date and then time如何订购带有日期和时间的 wp_query
【发布时间】:2020-06-21 08:47:12
【问题描述】:

我正在为事件使用带有单独日期和时间字段的高级自定义字段。我需要做的是显示所有尚未发生的事件。

到目前为止,我已设法按日期按事件顺序显示事件,但我现在需要做的是在事件发生时按顺序排列每个事件。时间一到,就需要从列表中删除该事件。

到目前为止,我的事件列表参数看起来像这样......

$today = date('Ymd');
$time = date('H:i:s');
$compCount = array(
  'post_type' => 'product',
  'posts_per_page'  => -1,
  'meta_query' => array(
    array(
      'key'     => 'comp_closing',
      'compare' => '>=',
      'value'       => $today,
    )
  ),
  'orderby'   => 'meta_value_num',
  'order'     => 'ASC',
);

我的日期字段是comp_closing,时间是closing_time

我曾尝试将 relation 与 2 个不同的元数组一起使用,但发现让任何东西正常工作都令人困惑。

【问题讨论】:

  • “我已经设法按日期顺序显示事件” - 我想那一定是偶然的 - 因为文档清楚地指出,当使用 @ 987654325@,'meta_key' => 'keyname'必须也存在,你目前缺少。
  • “我的日期字段是comp_closing,时间是closing_time - 那么你必须检查截止日期是否是今天 关闭时间晚于现在, 日期本身仍在未来。
  • @CBroe 感谢您的洞察力,如果您能向我解释这是如何完成的,那将非常有帮助。

标签: php wordpress advanced-custom-fields meta-query


【解决方案1】:

虽然我不知道comp_closingclosing_time 字段是如何存储在数据库中的,但这可能会为您指明正确的方向。

$today = date('Y-m-d');
$time = date('H:i:s');

$compCount = array(
  'post_type' => 'product',
  'posts_per_page'  => -1,
  'meta_query' => array(
    'relation' => 'OR',
    // make sure the date is after the current date...
    array(
      'key'     => 'comp_closing',
      'compare' => '>',
      'value'       => $today,
    ),
    // ...or if the date is the same...
    array(
      'relation' => 'AND',
      array(
        'key'     => 'comp_closing',
        'compare' => '=',
        'value'       => $today,
      ),
      // ...make sure we didn’t hit the time yet.
      array(
        'key'     => 'closing_time',
        'compare' => '>',
        'value'       => $time,
      )
    )
  ),
  'orderby'   => 'meta_value_num',
  'order'     => 'ASC',
);

【讨论】:

  • 谢谢!这对我来说确实有意义并且有效!我现在唯一需要做的就是确保如果我在同一天有多个事件,事件也按时间排序。所以最先结束的事件在列表的顶部。
  • This blog 帖子可以帮助您了解如何通过元键订购。我想知道您是否可以通过仅使用单个 datetime 字段作为日期来减轻痛苦。如果对您有帮助,请接受答案。 ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多